Tag:python Simple Web server implementation
Import socketimport reimport geventfrom gevent import Monkey Monkey.patch_all () # Recognize the wait time, let the co-process Switch def client_handler (client_ SOCKET): "Receive client link request, response corresponding data '" # receive data Request_data = CLIENT_SOCKET.RECV (4096) # to determine whether to receive data if not Request_data:print ("Guest The user has disconnected the link ") Client_socket.close () return # to decode the received client request data for decoding request_str_data = Request_data.decode () #对请求的报文进行分割, Split a request row list data_list = Request_str_data.split ("\ r \ n") # Get the request row data, the request row data is the No. 0 element of the list request_line = data_list[0] # Through regular matching to the file path we requested result = Re.match (r "\w+\s+ (\s+)", Request_line) # to determine if the matching request file path exists if not result:print ("Request path does not exist") client _socket.close () Return path_info = Result.group (1) Print ("User request information%s"% str (PATH_INFO)) # Set request domain default Jump home if Path_info = "/": # Specify the home address Path_info = "/index.html" # response header Response_header = "server:pws1.0\r\n" Try: # response body, open the data requested by the client with open ("./html" + Path_info, "RB") as File:file_data = File.read () except Exception as E: # Construction Request Error Response message Response_line = "http/1.1 404 Not F ound\r\n "response_body =" Eroor!!! %s ". Center (800)% (e) # splicing response message Response_data = Response_line + Response_header + "\ r \ n" + response_body # sends a response message to the client Client_socket.send (r Esponse_data.encode ()) Else: # Construct request successful response message Response_line = "http/1.1 ok\r\n" response_body = file_data Response_data = (Response_line + response_header + "\ r \ n"). Encode () + response_body # Send Response message client_socket.send (Response_data) Finally: # Close Socket Client_socket.close () # Create main function, define Socket DEF main (): # Create socket, specify IP and datagram type Server_socket = Socket.socket (Socket.af_inet, Socket. SOCK_STREAM) # Set port multiplexing server_socket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, True) # Set bindings, listen, Receive link server_socket.bind (("", 4433)) Server_socket.listen (128) # Server is for multi-client, loop receive client request link While true:client_socket, client_address = Server_socket.accept () print ("The service terminated a link request from%s"% str (client_address)) # Process link Request # Client_handler (client_socket) # Create a task to implement multitasking G1 = Gevent.spawn (Client_handler, client_socket) # Keep the main process alive (blocking the main process, Wait for the G1 to finish executing and then exit) # G1.join () # program entry if __name__ = = ' __main__ ': Main ()
Object-oriented encapsulation of the above code
Import socketimport reimport geventfrom gevent import Monkeyimport Sysmonkey.patch_all () # Recognize wait time, let the co-process switch class Httpserver ( Object): Def __init__ (self, port): "" "completes initialization of the instance object" "" # Create socket, specify IP and datagram type Server_socket = socket.so Cket (socket.af_inet, socket. SOCK_STREAM) # Set port multiplexing server_socket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, True) # Set bindings, listen, receive links server_socket.bind (("", 4433)) Server_socket.listen (128) # Reference to socket object self.server_socket = server_socket # socket link Wait def start (self): # server is for multi-client, loop receive client request link While true:client_socket, client_address = Self.server_socket.accept () print ("The service terminated a link request from%s"% s TR (client_address)) # Process link Request # Client_handler (client_socket) # Create a process to implement multi-tasking G1 = Gevent.spawn (Self.client_handler, Client_socket) # keeps the main process alive (blocking the main process, waiting for the co-G1 to finish executing and then exiting) #g1. Join () def CLI Ent_handler (self, client_socket): ' Receive client link request, response corresponding data ' ' # receive data Request_data = CLIENT_SOCKET.RECV (4096) # to determine if the data is received if Not Request_data:print ("Client has been disconnected") Client_socket.close () return # docking received client request data for Decode Request_str_data = Request_data.decode () #对请求的报文进行分割, split a request row list data_list = Request_str_data.spl It ("\ r \ n") # Gets the request line data, the request row data is the No. 0 element of the list request_line = data_list[0] # through the regular match to the file path we requested result = Re. Match (R "\w+\s+ (\s+)", Request_line) # determines if the matching request file path exists if not result:print ("Request path does not exist") Client_socket.close () Return path_info = Result.group (1) Print ("User request information%s"% str (PATH_INFO)) # Set request domain default Jump home if Path_info = = "/": # Specify Home Address Path_info = "/index.html" # response header Response_header = "server:pws1.0\r\n" Try: # response body, open the data requested by the client with open ("./html" + Path_info, "RB") as file: File_data = File.read () except Exception as E: # Construction Request Error Response message Response_line = "http/1.1 4 found\r\n "response_body =" Eroor!!! %s ". Center (+)% (e) # splicing response message Response_data = Response_line + Response_header +" \ r \ n "+ Response_bo DY # Send a response message to the client Client_socket.send (Response_data.encode ()) Else: # Construct request successful Response message Response_line = "http/1.1 ok\r\n" response_body = file_data Response_data = (Response_lin E + response_header + "\ r \ n"). Encode () + response_body # Send Response message client_socket.send (Response_data) Finally: # Close Socket Client_socket.close () # Create main function, define socket, set command line custom port run def main (): # Determine if the input command parameter Meet the requirements If Len (SYS.ARGV)! = 2:print ("Open correctly: Python3 Run program. PY Port number") return if Not Sys.argv[1].isdigit (): Print ("Correct open mode: Python3 Run program. PY Port number") return port = Int (sys.argv[1]) httP_server = Httpserver (port) Http_server.start () # program entry if __name__ = = ' __main__ ': Main ()
Python simple implementation Web server