Use SocketServer in Python to implement non-blocking communication between the client and the server.
The SocketServer module is used to implement non-blocking communication between the network client and the server.
First, let's take a look at the classes available for use in the SocketServer module:
BaseServer: contains the core functions of the server and hooks with the mix-in class. This class is only used for derivation, so instances of this class are not generated. You can consider using TCPServer and UDPServer.
TCPServer/UDPServer: the basic network synchronization TCP/UDP server.
UnixStreamServer/unixw.ramserver: A Basic file-based synchronous TCP/UDP server.
ForkingMixIn/ThreadingMixIn: implements the process or thread-based functions of the core. As a mixed class, it is used together with the server class to provide some asynchronous features. This class will not be directly instantiated.
ForkingTCPServer/ForkingUDPServer: A combination of ForkingMixIn and TCPServer/UDPServer.
BaseRequestHandler: contains core functions for processing service requests. This class is only used for derivation, so you can consider using StreamRequestHandler or DatagramRequestHandler for instances that do not generate this class.
StreamRequestHandler/DatagramRequestHandler: a service processing tool for TCP/UDP servers.
Next we will officially enter the topic. Here we use StreamRequestHandler and ThreadingTCPServer to achieve concurrent connection between the client and the server without blocking socket.
ThreadingTCPServer is derived from ThreadingMixIn. It mainly realizes the main process merging thread function.
StreamRequestHandler is mainly used for TCP/UDP Server service processing tools.
1. Create a SocketServerTCP Server
[Python] view plain copy # create SocketServerTCP server: import SocketServer from SocketServer import StreamRequestHandler as SRH from time import ctime host = 'xxx. xxx. xxx. xxx 'port = 9999 addr = (host, port) class Servers (SRH): def handle (self): print 'got connection from', self. client_address self. wfile. write ('Connection % s: % s at % s succeed! '% (Host, port, ctime () while True: data = self. request. recv (1024) if not data: break print data print "RECV from", self. client_address [0] self. request. send (data) print 'server is running .... 'server = SocketServer. threadingTCPServer (addr, Servers) server. serve_forever ()
2. Create a SocketServerTCP Client
[python] view plain copyfrom socket import * host = 'xxx.xxx.xxx.xxx' port = 9999 bufsize = 1024 addr = (host,port) client = socket(AF_INET,SOCK_STREAM) client.connect(addr) while True: data = raw_input() if not data or data=='exit': break client.send('%s\r\n' % data) data = client.recv(bufsize) if not data: break print data.strip() client.close()