Basic use of socketserver ----python

in hive-133802 •  4 years ago 

To meet our needs for a multi-threaded web server, the socketserver module is provided. socketserver uses IO multiplexing and a multi-threaded/process mechanism internally to implement a socket server that handles multiple client requests concurrently. Each time a client requests to connect to the server, the socketserver server creates a "thread" or "process" dedicated to handling all requests from the current client.

For the socketserver module, we most often use the ThreadingTCPServer class. It is defined as follows.

class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass

This function is inherited from two parent classes, ThreadingMixIn provides it with multi-threading capabilities and TCPServer provides it with basic socket communication capabilities. The inheritance relationship, as shown in the following figure.

截屏2021-02-04上午11.51.07.png

The ThreadingTCPServer implementation of the Soket server internally creates a thread for each client, which is used to interact with the client. The server is equivalent to a general manager, after receiving connections and creating new threads, communication is between the threads and the client!

The main point of using ThreadingTCPServer:
Initialize the controller class Handler [Handler is a class that inherits from BaseRequestHandler Handle method in Handler determines the operation of each connection over] [The class name of the controller class can be other, not necessarily Handler, as long as it inherits from BaseRequestHandler]

Create a class that inherits from socketserver.BaseRequestHandler.
init(): initializes the control settings, initializes the connection socket, address, handle instance and other information
handle(): defines how to handle each connection. You must define a method with the name handle, it cannot be any other name!
setup(): executed before handle(). Generally used to set a connection configuration other than the default
finish(): Executed after handle().
Manually start the ThreadingTCPServer.
The following is an example of the ThreadingTCPServer in use.

server:
截屏2021-02-04上午11.58.38.png
client:

截屏2021-02-04下午12.01.04.png

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!