May 4th python learning summary socketserver

 One, socketserver

SocketServer simplifies writing web servers.

It has 4 classes: TCPServer, UDPServer, UnixStreamServer, UnixDatagramServer. These four classes are processed synchronously, and asynchrony is supported 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 override its handle() method.

  2. Second, a server class must be instantiated, passing in the address of the server and the request handler class.

  3. Finally, call handle_request() (usually calling other event loops or using select()) or serve_forever().

When integrating the ThreadingMixIn class, you need to handle abnormal shutdown. daemon_threads indicates whether the server should wait for the thread to terminate. If the threads are independent of each other, it must be set to True, and the default is False.

Regardless of the network protocol used, the server class has the same external methods and properties.

This module has been renamed socketserver in python3.

server type

5 types: BaseServer, TCPServer, UnixStreamServer, UDPServer, UnixDatagramServer. Note: BaseServer does not directly serve externally.

server object

  • class SocketServer.BaseServer: This is the superclass for all 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.fileno(): Returns the integer file descriptor of the server listening socket. Typically used to pass to select.select() to allow one process to monitor multiple servers.

  • BaseServer.handle_request(): Handles a single request. Processing order: get_request(), verify_request(), process_request(). If the user provides the handle() method to throw an exception, the server's handle_error() method will be called. If no request is received within self.timeout, handle_timeout() will be called and handle_request() will be returned.

  • BaseServer.serve_forever(poll_interval=0.5): Process requests until an explicit shutdown() request. Poll shutdown every poll_interval seconds. ignore self.timeout. If you need to do periodic tasks, it is recommended to place them in other threads.

  • BaseServer.shutdown(): Tells serve_forever() to stop the loop and wait for it to stop. python2.6 version.

  • BaseServer.address_family: address family, such as socket.AF_INET and socket.AF_UNIX.

  • BaseServer.RequestHandlerClass: User-provided request handler class, this class creates an instance for each request.

  • BaseServer.server_address: The address on which the server listens. The format varies according to the protocol family address, see the documentation of the socket module.

  • BaseServer.socketSocket: The server on the server that listens for incoming request socket objects.

The server class supports the following class variables:

  • BaseServer.allow_reuse_address: Whether the server allows reuse of addresses. Defaults to false and can be changed in subclasses.

  • BaseServer.request_queue_size

The size of the request queue. If a single request takes a long time to process, requests are placed in a queue when the server is busy, up to request_queue_size. Once the queue is full, requests from clients will get "Connection denied" errors. The default is usually 5, but can be overridden by subclasses.

  • BaseServer.socket_type: The socket type used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM etc.

  • BaseServer.timeout: Timeout time in seconds, or None for no timeout. If handle_request() does not receive a request within timeout, handle_timeout() will be called.

The following methods can be overridden by subclasses, and they have no effect on external users of the server object.

  • BaseServer.finish_request(): actually handles the request initiated by RequestHandlerClass and calls its handle() method. Commonly used.

  • BaseServer.get_request(): accepts a socket request and returns a 2-tuple containing the new socket object to be used to communicate with the client, and the address of the client.

  • BaseServer.handle_error(request, client_address): Called if the handle() method of RequestHandlerClass throws an exception. The default action is to print a traceback to stdout and continue processing other requests.

  • BaseServer.handle_timeout(): Timeout processing. The default is to collect the exited child process status for the forking server, and the threading server does nothing.

  • BaseServer.process_request(request, client_address) : call finish_request() to create an instance of RequestHandlerClass. If needed, this feature can create new processes or threads to handle requests. The ForkingMixIn and ThreadingMixIn classes do this. Commonly used.

  • BaseServer.server_activate(): Activate the server through the server's constructor. The default behavior is just listening on the server socket. Overloadable.

  • BaseServer.server_bind(): Bind the socket to the desired address by calling the server's constructor. Overloadable.

  • BaseServer.verify_request(request, client_address): Returns a boolean value, if the value is True, the request will be processed, otherwise the request will be rejected. This function can be overridden to implement access control to the server. The default implementation always returns True. client_address can limit the client, such as only processing requests in the specified ip range. Commonly used.

request handler

The processor receives the data and decides what to do. It is responsible for implementing protocols (ie, HTTP, XML-RPC, or AMQP) on top of the socket layer, reading data, processing and writing responses. The methods that can be overloaded are as follows:

  • setup(): Prepares for request processing. By default, it does nothing, and a file-like object is created in StreamRequestHandler to read and write sockets.

  • handle(): handles the request. Parse incoming requests, process data, and send responses. Do nothing by default. Common variables: self.request, self.client_address, self.server.

  • finish(): Environment cleanup. Do nothing by default. If setup generates an exception, finish will not be executed.

Usually it is only necessary to overload handle. The type of self.request is not the same as the datagram or stream service. For streaming services, self.request is the socket object; for datagram services, self.request is a string and socket. Can be overloaded in subclasses StreamRequestHandler or DatagramRequestHandler, override setup() and finish(), and provide self.rfile and self.wfile properties. self.rfile and self.wfile can be read or written to obtain request data or return data to the client.

Example:

Based on TCP:

import socketserver

# 通信循环
class MytcpHandler(socketserver.BaseRequestHandler):
    def hahahahahahahh(self):
        while True:
            try:
                data = self.request.recv(1024)   # 1024 The maximum limit of received data 
                if  not data: break #For   linux system 
                self.request.send(data.upper()) #Note   : Sending and receiving are all in bytes except ConnectionResetError :
                 break
            
        self.request.close()


if  __name__ == ' __main__ ' :
     #Connection loop 
    server=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)

 

UDP based:

import socketserver

#Communication loop 
class MyUDPHandler(socketserver.BaseRequestHandler):
     def handle(self):
         # print(self.request) 
        res= self.request[0]
         print ( ' Data sent by client: ' ,res)

        self.request[1].sendto(res.upper(),self.client_address)


if  __name__ == ' __main__ ' :
     #Connection loop 
    server=socketserver.ThreadingUDPServer(( ' 127.0.0.1 ' ,8080 ),MyUDPHandler)
    server.serve_forever()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325470189&siteId=291194637