The key to tcp-based sockets is two loops, a link loop and a communication loop
The socketserver module is divided into two categories: server class (solving link problems) and request class (solving communication problems)
server class:
request class:
Inheritance relationship:
Take the following code as an example to analyze the socketserver source code:
ftpserver=socketserver.ThreadingTCPServer(('127.0.0.1',8080),FtpServer)
ftpserver.serve_forever()
The order of finding properties: ThreadingTCPServer->ThreadingMixIn->TCPServer->BaseServer
- Instantiate to get ftpserver, first find __init__ of class ThreadingTCPServer, find it in TCPServer, and then execute server_bind, server_active
- Find serve_forever under ftpserver, find it in BaseServer, and then execute self._handle_request_noblock(), which is also in BaseServer
- Execute self._handle_request_noblock() and then execute request, client_address = self.get_request() (that is, self.socket.accept() in TCPServer), then execute self.process_request(request, client_address)
- Find process_request in ThreadingMixIn, enable multithreading to deal with concurrency, then execute process_request_thread, execute self.finish_request(request, client_address)
- The above four parts complete the link cycle. This part begins to process the communication part, find the finish_request in BaseServer, trigger the instantiation of our own defined class, and find the __init__ method, and our own defined class does not have this method, then Go to its parent class, which is BaseRequestHandler....
Source code analysis summary:
Based on tcp socketserver in our own defined class
- self.server is the socket object
- self.request is a link
- self.client_address is the client address
udp-based socketserver in our own defined class
- self.request is a tuple (the first element is the data sent by the client, and the second part is the udp socket object of the server), such as (b'adsf', <socket.socket fd=200, family= AddressFamily.AF_INET, type=SocketKind.SOCK_DGRAM, proto=0, laddr=('127.0.0.1', 8080)>)
- self.client_address is the client address