Write the socket program in Python and listen to the service on the specified port:
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Port = 8080
Sock.bind (("', port)")
Sock.listen (1)
print ' Listening on port:%s '% port
While True:
Try
conn, addr = Sock.accept ()
print ' connected by%s:%s '% (addr[0], addr[1])
Except Keyboardinterrupt:
Break
Except Socket.error, msg:
print '%s '% msg
Provides a socket service on the port, terminates the program after the connection, and then runs the program again with an error message:
...
Socket.error: [Errno] Address already in use
You can resolve these issues by setting the socket reuse option SO_REUSEADDR, such as:
Import socket
Port = 8080
Server = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Server.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)
Server.bind (("', port)")
Server.listen (1)
print ' Listening on port:%s '% port
While True:
Try
conn, addr = Server.accept ()
print ' connected by%s:%s '% (addr[0], addr[1])
Except Keyboardinterrupt:
Break
Except Socket.error, msg:
print '%s '% msg
Tips:
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
state = sock.getsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR) # Get socket so_reuseaddr option status
print ' State state:%s '% State
Sock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) #设置套接字选项
state = sock.getsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR)
print ' State state:%s '% State
Note: You can use the Telnet command to debug
www.pythonfan.org
Socket Port Reuse