Use the SocketServer module to realize concurrent connection and non-blocking communication between the network client and the server
First, let’s understand the classes available in the SocketServer module:
BaseServer: Contains the core of the server The function is hooked to the mix-in class; this class is only used for derivation, so instances of this class will not be generated; consider using TCPServer and UDPServer.
TCPServer/UDPServer: Basic network synchronization TCP/UDP server.
UnixStreamServer/ UnixDatagramServer: Basic file-based synchronization TCP/UDP server.
ForkingMixIn/ ThreadingMixIn: Implements the core process or threading functions; as a hybrid class, used together with the server class to provide some asynchronous features; this class will not be instantiated directly.
ForkingTCPServer/ForkingUDPServer: A combination of ForkingMixIn and TCPServer/UDPServer.
BaseRequestHandler: Contains the core functionality for handling service requests. This class is only for derivation, so instances of this class will not be generated. Consider using StreamRequestHandler or DatagramRequestHandler.
StreamRequestHandler/ DatagramRequestHandler: Service processing tool for TCP/UDP servers.
Now we officially enter the topic. Here we use StreamRequestHandler and ThreadingTCPServer to realize concurrent connections between the client and the server and non-blocking sockets.
ThreadingTCPServer is derived from ThreadingMixIn and mainly implements the core process combination and threading functions.
StreamRequestHandler is mainly used as a service processing tool for TCP/UDP servers.
1. Create SocketServerTCP server
#创建SocketServerTCP服务器: 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 SocketServerTCP client
#from socket from socket import * host = 'xxx.xxx.xxx.xxx' port = 9999 bufsize = 1024 addr = (host,port) #client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 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()
The above is the detailed content of Introduction to the method of realizing non-blocking communication between client and server using SocketServer in Python. For more information, please follow other related articles on the PHP Chinese website!