Simple web server implementation

 

Case: Fixed-page http server

Import Socket
 DEF service_client (Since the software of):
     "" " for the data returned to the client " "" 
    # 1. Receive a request sent from a browser, i.e., an http request 
    # the GET /HTTP/1.1 
    # ...... 
    Request = Since the software of .recv (1024 )
     Print (Request)
     # 2. http return data format to the browser 
    # 2.1 ready to send data to the browser header --- 
    Response = " the hTTP / 1.1 200 is the OK \ R & lt \ n- " 
    Response + = " \ r \ the n- " 
    # 2.2 is ready to send data to the browser Boy --- 
    the Response + = " hahahaha " 
    new_socket.send (the Response.encode(". 8-UTF " ))
     # close the socket 
    new_socket.close () 

DEF main ():
     " "" is used to complete the overall control "" " 
    # 1. Create a socket 
    tcp_server_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
     # 2. bind 
    tcp_server_socket.bind (( "" , 7890 ))
     # 3. turns listening socket 
    tcp_server_socket.listen (128 )
     the while True:
         # 4. wait for new clients link 
        new_socket, client_addr = tcp_server_socket.accept ()
         # 5. for this client service 
        service_client (new_socket)
    # Close the listening socket 
    tcp_server_socket.close ()
 IF  __name__ == " __main__ " : 
    main ()

 

Guess you like

Origin www.cnblogs.com/ql0302/p/11404536.html