The Socketserver module in Python3 simplifies the task of writing Web servers
In the actual development, especially in the case of multiple concurrency, the socket module is obviously of little use to us, because if you are going through the socket module to implement the concurrent socket communication, it is too troublesome, the Socketserver module is python to provide you with a ready-made interface, You only need to write a small amount of code, you can achieve your needs
First, you must BaseRequestHandler
create a request handler class by subclasses the class and overriding its methods, which handle()
will handle incoming requests. Second, you must instantiate a server class that passes it to the server's address and request handler class. the server object's or method is then invoked handle_request()
serve_forever()
to process one or more requests. Finally, call server_close()
close socket
ImportSocketserverclassThreadedtcprequesthandler (socketserver. Baserequesthandler):"""the Baserequesthandler class must be inherited, overriding the handle () method""" defhandle (self): result= SELF.REQUEST.RECV (1024) Data= str (result,'Utf-8') Print(data) rep_msg= Input (">>>") self.request.send (bytes (rep_msg,"Utf-8"))#Running the serviceif __name__=="__main__": HOST, PORT="127.0.0.1", 9999#instantiate the corresponding class as needed, and provide the address and the implementation of the request processing class #class Socketserver. Forkingtcpserver #class Socketserver. Forkingudpserver #class Socketserver. Threadingtcpserver #class Socketserver. ThreadingudpserverServer =Socketserver. Threadingtcpserver (HOST, PORT), Threadedtcprequesthandler) Server.serve_forever ()
Service Side
ImportSockethost, PORT="127.0.0.1", 9999 whileTrue:with Socket.socket () as Sk_client:sk_client.connect ((HOST, PORT)) req_msg= Input (">>>") sk_client.send (bytes (req_msg,'UTF8')) Rep_msg= SK_CLIENT.RECV (1024) Print(Str (REP_MSG,"Utf-8"))
Client
Resources
Http://python.usyiyi.cn/translate/python_352/library/socketserver.html
Python3-socketserver Module-network server framework