Section XVII single-process, single-threaded, non-blocking concurrency verification

Import socket 

'' ' 
used to verify the realization of the principle of coroutines, in addition to direct multi-process multiple tasks, multi-threaded and multi-threaded nature of the blocking time is the use of other data processing 
processes in parallel, while running real; coroutine threads and are concurrent, is to use the time interval in turn calls 
' '' 

TCP_SOCKET = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 
tcp_socket.bind (( '' , 8080 )) 
tcp_socket.listen ( 128 ) 
TCP_SOCKET. setblocking (False)   # set the socket is blocked manner, releasing accept () blocking 
client_socket_list = List () 

the while True:
     the try : 
        Since the software of, to new_addr = tcp_socket.accept ()
     the except Exception AS E:
         Print ( 'No new client arrival ' )
     the else : 
        client_socket_list.append (Since the software of)         
        Print ( ' no abnormality occurs to a client ' ) 
        new_socket.setblocking (False)   # new socket is provided the socket is blocked way, unblocked when calling recv method waits for the client to send data 
    for client_socket in client_socket_list:
         the try : 
            recv_data = client_socket.recv (1024 )
         the except Exception AS E:
             Print ( ' this client also did not send data over ' )
         the else :
             Print (' Has received information that the client ' )
             Print (recv_data)
             IF recv_data:
                 Print ( " client sends data " )
             the else :   # client calls the close (), resulting in data transmission over the empty 
                client_socket.close ()   # close the socket 
                client_socket_list.remove (client_socket)   # this interaction has been completed socket to remove it out of the list

 

Guess you like

Origin www.cnblogs.com/kogmaw/p/12602508.html