First, Socketserver
Socketserver simplifies the writing of Web servers.
It has 4 classes: Tcpserver,udpserver,unixstreamserver,unixdatagramserver. These 4 classes are processed synchronously and are supported asynchronously through the Forkingmixin and ThreadingMixIn classes.
Steps to create a server:
1 . First, you must create a request processing class, which is a subclass of Baserequesthandler and overloads its handle () method.
2. Second, you must instantiate a server class, the address of the incoming server, and the request handler class.
3. Finally, call Handle_request () (usually call other event loops or use Select ()) or Serve_forever ().
When you integrate the ThreadingMixIn class, you need to handle exception shutdown. Daemon_threads indicates whether the server waits for thread termination, and if the threads are independent of each other, they must be set to TRUE and the default is False.
The server class has the same external methods and properties regardless of the network protocol.
The module has been renamed to Socketserver in Python3.
Server type
5 types: Baseserver,tcpserver,unixstreamserver,udpserver,unixdatagramserver. Note: Baseserver does not serve directly to the outside.
Server object
Class Socketserver.baseserver: This is the superclass of all the server objects in the module. It defines the interface, as described below, but most of the methods are not implemented and are refined in subclasses.
Baseserver.handle_request (): Processes a single request. Processing order: Get_request (), Verify_request (), Process_request (). If the user provides the handle () method throws an exception, the server's Handle_error () method is called. If no request is received within the Self.timeout, the Handle_timeout () is called and the Handle_request () is returned.
The server class supports the following class variables:
The size of the request queue. If a single request takes a long time to process, the server is busy when the request is placed in the queue, up to a maximum of request_queue_size. Once the queue is full, requests from the client will get a "Connection denied" error. The default value is typically 5, but can be overridden by a quilt class.
Baseserver.timeout: Timeout, in seconds, or none means no time-out. If Handle_request () does not receive a request within a timeout, handle_timeout () is called.
The following methods can be overridden by subclasses, which have no effect on external users of server objects.
Baseserver.process_request (Request, client_address): Call Finish_request () to create an instance of Requesthandlerclass. If required, this feature can create new processes or threads to handle requests, which the Forkingmixin and ThreadingMixIn classes do. Common.
Baseserver.verify_request (Request, client_address): Returns a Boolean value that, if true, will be processed and the request will be rejected. This feature can be overridden to implement access control to the server. The default implementation always returns TRUE. The client_address can restrict the client, such as the request to handle only the specified IP range. Common.
Request processor
The processor receives the data and decides what to do. It is responsible for implementing protocols on top of the socket layer (i.e., HTTP, XML-RPC, or AMQP), reading data, processing, and writing reactions. The following methods can be overloaded:
Setup (): Prepares request processing. By default, nothing is done, and Streamrequesthandler creates a file-like object to read and write to the socket.
Handle (): Process the request. Resolves incoming requests, processes data, and sends a response. Nothing is done by default. Common variables: Self.request,self.client_address,self.server.
Finish (): Environment cleanup. Nothing is done by default, and if Setup produces an exception, the finish is not executed.
Typically, you only need to overload handle. The type of self.request differs from the service of the datagram or stream. For streaming services, Self.request is the socket object; For datagram services, Self.request is a string and a socket. You can overload in subclasses Streamrequesthandler or Datagramrequesthandler, rewrite setup () and finish (), and provide Self.rfile and Self.wfile properties. Self.rfile and Self.wfile can read or write to obtain the requested data or return the data to the client.
Instance:
Based on TCP:
ImportSocketserver#Communication CycleclassMytcphandler (socketserver. Baserequesthandler):defHahahahahahahh (self): whileTrue:Try: Data= SELF.REQUEST.RECV (1024)#1024 maximum limit of received data if notData Break #for Linux SystemsSelf.request.send (Data.upper ())#Note: The sending and receiving are all in bytes units exceptConnectionreseterror: Breakself.request.close ()if __name__=='__main__': #Connecting LoopsServer=socketserver. Threadingtcpserver (('127.0.0.1', 8080), Mytcphandler) Server.serve_forever ()Print(server.server_address)Print(server. Requesthandlerclass)Print(Server.socket)#Conn,client_addr=sock.accpet ()#request, client_address = Self.get_request ()#self.process_request (conn, client_address)#self.finish_request (conn, client_address)#Obj=mytcphandler (conn,client_address,server)
Based on UDP:
ImportSocketserver#Communication CycleclassMyudphandler (socketserver. Baserequesthandler):defhandle (self):#print (self.request)res=Self.request[0]Print('data sent by the client:', res) self.request[1].sendto (Res.upper (), self.client_address)if __name__=='__main__': #Connecting LoopsServer=socketserver. Threadingudpserver (('127.0.0.1', 8080), Myudphandler) Server.serve_forever ()
May 4 Python Learning summary socketserver