Section XV using multiple threads to complete http server

Import Socket
 Import Threading 

DEF tcp_serve (resp_socket): 
    recv_data = resp_socket.recv (1024 )
     Print (recv_data) 
    resp_data = ' the HTTP / 1.1 200 is the OK \ R & lt \ n- ' + " \ R & lt \ n- " + ' hahaha ' 
    # browser identification the breaking behavior \ R & lt \ n- 
    resp_socket.send (resp_data.encode ( ' UTF-. 8 ' )) 
    resp_socket.close () 

DEF main ():
     "" " 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 client feedback 
    web_socket.bind (( ' 192.168.0.106 ' , 8080 )) 
    web_socket.listen ( 128 )
     while True:     
        resp_socket, resp_addr = web_socket.accept ()
         '' ' three-way handshake is successful server start calling accept, 
        when while It began to launch the first cycle connect, then the server handshake to successfully start their service, that send data at this time if a second client initiated the request, 
        the second client will wait for the server to complete the first client service to accept new link 
        which resulted in a second client to wait
        So 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 is not to reduce the time to shake hands, but reduce service latency 
        '' ' 
        # tcp_serve ( resp_socket) 
        t = threading.Thread (target = tcp_serve, args = (resp_socket,)) 
        t.start () 
        # resp_socket.close ()   
        # seems to need it in Ubuntu, because everything is in Ubuntu 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/12602498.html