Section XVI complete http server using coroutines

Import socket
 Import gevent
 from gevent Import Monkey 

monkey.patch_all () 

DEF tcp_serve (resp_socket): 
    recv_data = resp_socket.recv (1024 )
     # is blocked waiting for the client to the data, will proceed to the next step after 
    Print (recv_data) 
    resp_data = ' the HTTP / 1.1 200 is the OK \ R & lt \ n- ' + " \ R & lt \ n- " + ' hahaha ' 
    # transducer browser behavior recognition \ R & lt \ n- 
    resp_socket.send (resp_data.encode ( ' UTF-. 8 ' )) 
    resp_socket.close () 

DEFmain ():
     "" " a simple web server " ""     
    # 1, create word suite 
    # 128 is the number of links biggest client is running 
    web_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 
    web_socket.setsockopt (socket.SOL_SOCKET , socket.SO_REUSEADDR, 1 )
     # If you force the server to call close, you need to convert again to link the port, or port will be occupied wait for client feedback 
    web_socket.bind (( ' 192.168.0.106 ' , 8080 )) 
    web_socket.listen ( 128 )
     the while True:     
        resp_socket, resp_addr = web_socket.accept ()
         '' ' three-way handshake is successful server start calling accept,
        When the start of the cycle while the first initiating connect, the server starts a handshake success and its services, i.e. data transmission, if at this time the second client sends a request, 
        the second client to the first server will wait for a client service is unable to accept new link 
        which resulted in a second client to wait for 
        it to create a multi-tasking, for the first client to shake hands after the success of individual services, can reduce the waiting time of the second client, 
        so the role of multi-tasking and not to reduce the time to shake hands, but reduce service latency 
        '' ' 
        # tcp_serve (resp_socket) 
        gevent.spawn (tcp_serve, resp_socket)
         # resp_socket.close ()   
        # He seems to need it in Ubuntu, because Ubuntu where everything is a file, multi-copy process, resulting in a more than two resp_socket of file descriptors, window seems not, there are no effect 
    web_socket.close () 


IF  __name__ == ' __main__ ' : 
    main ()

 

Guess you like

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