Non-blocking thought to achieve single-process single-thread TCP server concurrency

Set the socket to the default non-blocking state, and use the trap exception to handle the abnormality of the socket due to non-blocking, to achieve the normal operation of the program. The effects are as follows:

 

 

1  import socket
 2  
3  
4  def main ():
 5      tcp_server_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
 6      tcp_server_socket.bind (( '' , 7788 ))
 7      tcp_server_socket.listen (128 )
 8      tcp_server_socket.setblocking ( false)   # set non-clogging listening socket 
. 9  
10      client_socket_list = list ()    # provided a list storing client socket 
. 11      the while True:
 12 is          the try :
 13 is              Since the software of, client_addr =tcp_server_socket.accept ()
 14          the except :
 15              Pass 
16              # Print ( "no new client connections") 
. 17          the else :
 18 is              Print ( " to the client " )
 . 19              new_socket.setblocking (False)   # Set client socket non-clogging word 
20 is              client_socket_list.append (Since the software of)
 21 is  
22 is          # list is empty is not performed for loop 
23 is          for client_socket in client_socket_list:
 24              the try :
 25                  recv_data = client_socket.recv (1024 )
26 is              the except :
 27                  Pass 
28                  # Print ( "not received data from the client") 
29              the else :
 30                  IF recv_data:
 31 is                      Print (recv_data.decode ( ' UTF-. 8 ' ))
 32                  # when there recv but no data is received, Prove that the client closed the connection 
33                  else :
 34                      client_socket_list.remove (client_socket)
 35                      client_socket.close ()
 36  
37  
38  if  __name__ == ' __main__ ' :
 39      main ()

Guess you like

Origin www.cnblogs.com/zuzhuangmengxiang/p/12688298.html