Socketserver
This module simplifies the writing of sockets.
1, it has a base class, defines how to establish a connection. Baseserver provides a service class interface, and Baseserver uses Select to create multithreading. Baseserver There are four classes: TCPServer, Unixstreamserver, Udpserver, Unixdatagramserver.
2. It also provides a request processing class: Defines how user data is processed. Defines three methods Setup\handler\finish, the interface, when used, re-write the corresponding method.
3. Using Forktheard and
BASESERVER Module Structure:
Service Processing class methods:
|
Role
|
Baseserver
|
Hyper-class, which provides the API and uses select to create multithreading. It cannot be used directly by calling it.
|
TCPServer
|
Creates a socket for each process that transmits TCP data. At the same time, it is also a base class.
|
Udpserver
|
transmits UDP data. |
Unixstreamserver
|
Use under Unix
|
Unixdatagramserver |
Use under Unix
|
Methods of service Processing class Baseserver
|
Role
|
Fileno ()
|
Returns an integer file descriptor for the server listener socket. Typically used to pass to Select.select () to allow a process to monitor multiple servers.
|
Handle_request ()
|
Process 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.
|
Serve_forever (poll_interval=0.5) |
Processes the request until an explicit shutdown () request is made. Polls every poll_interval seconds for shutdown. Ignore Self.timeout. If you need to do periodic tasks, it is recommended to place them on other threads. |
Shutdown ()
|
Tell Serve_forever () to stop. For python2.6.
|
Address_family
|
Address families. Socket.af_inet, etc.
|
Handlerrequestclass
|
A user-supplied request processing class that creates an instance for each request.
|
Server_address
|
The server address on which to listen.
|
Socketsocket
|
The server on the server that listens for incoming requests to the socket object. |
|
|
The following methods can be overridden by subclasses, which have no effect on external users of server objects. |
Finish_request () |
The Requesthandlerclass initiated request is actually processed and its handle () method is called. Common. |
Get_request () |
Accepts a socket request and returns a two-tuple that contains the new socket object to be used to communicate with the client, and the address of the client.
|
Handle_error (Request, client_address) |
Called If the Requesthandlerclass handle () method throws an exception. The default action is to print Traceback to standard output and continue processing other requests. |
Handle_timeout () |
Timeout processing. By default, the forking server is a child process state that collects exits, and the threading server does nothing |
Process_request (Request, client_address)
|
Call Finish_request () to create an instance of the Requesthandlerclass. If required, this feature can create new processes or threads to handle requests, which the Forkingmixin and ThreadingMixIn classes do. Common. |
Server_activate () |
Activate the server by using the server's constructor. The default behavior is to listen only to the server socket. can be overloaded. |
Server_bind () |
Call the bind socket to the desired address through the server's constructor. can be overloaded. |
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. |
|
|
Variables (attributes) for the service processing class:
|
Role
|
Allow_reuse_address
|
If address reuse is allowed, the default is false and can be changed in subclasses.
|
Request_queue_size
|
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. |
Socket_type
|
The socket type that the server uses, socket. Sock_stream and Socket.sock_dgram and so on. |
Timeout
|
The time-out period. In seconds, or none indicates no time-out. If Handle_request () does not receive a request within a timeout, handle_timeout () is called. |
|
|
Method of request Processing class:
|
Role
|
Setup ()
|
The method before the request is processed and can be initialized.
|
Handler ()
|
Processes the requested method and processes the content with the client interaction.
|
Finish ()
|
Handler () The method to run after processing is complete. For release and cleanup.
|
|
|
#服务端: Import socketserverclass mysite (socketserver. Baserequesthandler): # must inherit Socketserver base class def handler (self): # rewrite the handler () method in the base class to handle receiving, sending requests in this method while true: recv_data = SELF.REQUEST.RECV (1024x768) data = json.loads (Recv_data.decode ()) # Why use JSON? Because I like it. This wraps numbers, characters, lists, and so on data types all-in-    &NBSp; print (data) if data.lower () == "Exit": # detected exit exit print ("Client Exit! ") break self.request.send (Json.dumps (Data.lower ()). Encode ()) # sends the converted lowercase data to the client and then goes to the next loop my_server = socketserver. TCPServer (("localhost", 9999), mysite) # instantiates the Socketserver and transmits the server IP, port, and subclass My_server.serve_forever () # client import Socket class myclient (object): def __init__ (obj): # Receive a socket instantiated object self.conn = obj def handler (Self,ip,prot): # define a method for data interaction self.conn.connect ((ip,port)) # binding links, is it better to put it in the Init method? while ture: # loop send, receive data cmd = input (' input converted characters, exit exit! ') if cmd.strip (). Lower () == ' exit ': # if input exit exits print (' Exit! ') break &nbSp; self.conn.send (Json.dumps (cmd ). Encode ()) # send input data RECV_DATA = SELF.CONN.RECV (1024x768) # receive server-converted data data = Json.loads (Recv_data.decode ()) # json decoding print (' converted: {} '. Format (data)) my_socket = socket.socket () # instantiating a Socket object My_client = myclient (my_ SOCKET) # instantiate a custom class and pass in the instantiated socket object My_ Client.handler ("localhost", 9999) # Call Data interaction method "" "Above code blog praying holding hands hit, untested. "" "
Other references:
Https://www.cnblogs.com/MnCu8261/p/5546823.html
Https://www.cnblogs.com/sunailong/p/5058786.html
Https://www.cnblogs.com/eric_yi/p/7701381.html
Python Basics: Network Programming Socketserver Advanced Chapter