Using the socket to write a simple server step parsing the socket object
This step is the same as the last time we used the socket as a client, we need to have a socket connection
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
Set socket options (setsockopt)
Options Introduction
setsockopt (set socket option), parameter format: setsockopt (Level,optname,value)
The relationship of each option:
The 1.level:level setting determines the options that optname can use
2.optname: Determined by level
3.value: Determined by level and optname
Options
Level:sol_socket
When level is sol_socket, the common options that optname can use are:
Bind address and port number (bind socket)
As a server, if you provide access, you must have an IP address and port number for client access.
# 绑定地址为192.168.128.128 端口号为 12345s.bind((‘192.168.128.128‘,12345))
Listening connection (listen)
Listen for the ip:port that bind well
# 5 代表着允许5个连接在队列中等待。s.listen(5)
Accept connection (accepted)
Accept client Connections
Instance
Script writing
[[email protected] network]# cat socket_server.py #!/usr/bin/env python# 导入socket模块import socket# 配置host和porthost = ‘192.168.128.128‘port = 1234# 新建一个socket连接s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)# 设置socket参数s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)# 绑定IP和端口s.bind((host,port))# 监听s.listen(5)# 用while循环一直接受连接,如果不配置while循环,程序执行一次就退出了while 1: # 接受连接,并把客户端的连接信息赋值给clientsock,和clientaddr clientsock,clientaddr = s.accept() # 打印客户端的信息 print "Got connection from",clientsock.getpeername() # 关闭连接
Run the program
Viewing the Listening port
[[email protected] ~]# netstat -ant | grep 1234tcp 0 0 192.168.128.128:1234 0.0.0.0:* LISTEN tcp 0 0 192.168.128.128:1234 192.168.128.128:33232 TIME_WAIT
Client connections
telnet 192.168.128.128 1234
View server-side reactions
[[email protected] network]# python socket_server.py Got connection from (‘192.168.128.1‘, 2839)
[Python network programming] using sockets to write a simple server