Non blocking communication between client and server is realized by using SocketServer in Python
- 2020-05-17 05:52:52
- OfStack
The SocketServer module is used to realize the concurrent connection non-blocking communication between the network client and the server.
First, take a look at the classes available in the SocketServer module:
BaseServer: contains the core functions of the server and the mixing (mix-in) class; This class is only used for derivation, so no instance of this class will be generated; Consider using TCPServer and UDPServer.
TCPServer/UDPServer: basic network synchronization with TCP/UDP servers.
UnixStreamServer/ UnixDatagramServer: basic file based synchronization of TCP/UDP servers.
ForkingMixIn/ ThreadingMixIn: implements the core process or threading functions; As a hybrid class, it is used with server class 1 to provide some asynchronous features. This class is not instantiated directly.
ForkingTCPServer/ ForkingUDPServer: a combination of ForkingMixIn and TCPServer/UDPServer.
BaseRequestHandler: contains the core functionality for handling service requests. This class is only used for derivation, so you can consider using StreamRequestHandler or DatagramRequestHandler if an instance of this class will not be generated.
StreamRequestHandler/ DatagramRequestHandler: service processing tool for TCP/UDP servers.
Now let's get into the topic. Here we use StreamRequestHandler and ThreadingTCPServer to realize the concurrent connection between the client and the server without blocking socket.
ThreadingTCPServer, derived from ThreadingMixIn, mainly implements the core process combination threading function.
StreamRequestHandler is primarily used as a service processing tool for TCP/UDP servers.
1. Create 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 SocketServerTCP client
[python] view plain copy
from 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()