1. Use Python to write a static Web server that can handle HTTP requests for static pages
Principle:
A. Using the socket for communication between the server and the browser
B. Using multithreading to handle requests from multiple client browsers
C. Sending response data using the HTTP protocol
Realize:
# coding:utf-8import socketfrom multiprocessing import processdef handle_request (client_socket): request_data = CLIENT_SOCKET.RECV (1024x768) response_first_line = "http/1.1 ok\r\n" response_headers = "Server:my Web Static server\r\n " response_body =" Hello, My Web Static Server " response = response_first_line + response_headers +" \r\ N "+ response_body client_socket.send (bytes (response, encoding=" UTF-8 ")) client_socket.close () If __name__ = = "__main__": server_socket = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Server_socket.bind (("", 8001)) Server_socket.listen (+) while True: client_ Socket, client_address = server_socket.accept () print (' ['%s ', '%s '] user already connected to the server! '% client_address) handler = Process (Target=handle_request, args= (Client_socket,)) Handler.start () Client_socket.close ()
The design of Python Web server