The Socketserver module is the encapsulation of the socket module.
The socketserver
module simplifies the task of writing network servers.
Socketserver There are so many different types
1 |
class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate = True ) |
This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server.
1 |
class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate = True ) |
This uses datagrams, which is discrete packets of information that may arrive out of order or is lost while in transit. The parameters is the same as for TCPServer
.
12 |
class socketserver. Unixstreamserver (server_address, Requesthandlerclass, bind_and_activate = true ) Class socketserver. Unixdatagramserver (server_address, requesthandlerclass,bind_and_activate = true ) |
These more infrequently used classes is similar to the TCP and UDP classes, but use Unix domain sockets; They ' re not available on Non-unix platforms. The parameters is the same as for TCPServer
.
There is five classes in a inheritance diagram, four of the which represent synchronous servers of four types:
+------------+| v+------------------+| v+--------------------+| +--------------------+
Create a socketserver at least in the following steps:
First, you must create a request handler handle class by subclassing the Baserequesthandler class and overriding cover
Its handle () method; This method would process incoming requests.
You have to create a request processing class yourself, and this class inherits Baserequesthandler, and there are handle that rewrite the Father's class ().
Second, you must instantiate instantiate one of the server classes, passing it the server ' s address and the request handler class.
You must instantiate the TCPServer and pass the server IP and the request processing class you created above to this tcpserver
Then call the Handle_request () or Serve_forever () method of the server object to process one or many requests.
Server.handle_request () #只处理一个请求
Server.serve_forever () #处理多个一个请求, always execute
To make your socketserver concurrent, you must choose to use one of the following multiple concurrency classes
Classsocketserver.
ForkingTCPServer
Classsocketserver.
ForkingUDPServer
Classsocketserver.
ThreadingTCPServer
Classsocketserver.
ThreadingUDPServer
Basic Socketserver Code
1 ImportSocketserver2 3 classMytcphandler (socketserver. Baserequesthandler):4 defhandle (self):5 whileTrue:6 Try:7Self.data = SELF.REQUEST.RECV (1024). Strip ()8 Print("{} wrote:". Format (Self.client_address[0]))9 Print(Self.data)Ten Self.request.send (Self.data.upper ()) One exceptConnectionreseterror as E: A Print("Err", E) - Break - if __name__=="__main__": theHOST, PORT ="localhost", 9999 - #Create the server, binding to localhost on port 9999 -Server =Socketserver. Threadingtcpserver (HOST, PORT), Mytcphandler) -Server.serve_forever ()
Python Learning--socketserver Module