socketserver

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

  1. Instantiate to get ftpserver, first find __init__ of class ThreadingTCPServer, find it in TCPServer, and then execute server_bind, server_active
  2. Find serve_forever under ftpserver, find it in BaseServer, and then execute self._handle_request_noblock(), which is also in BaseServer
  3. 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)
  4. Find process_request in ThreadingMixIn, enable multithreading to deal with concurrency, then execute process_request_thread, execute self.finish_request(request, client_address)
  5. 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

  1.   self.server is the socket object
  2.   self.request is a link
  3.   self.client_address is the client address

udp-based socketserver in our own defined class

  1.   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)>)
  2.   self.client_address is the client address

Guess you like

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