下面我们正式进入主题,这里我们采用StreamRequestHandler和ThreadingTCPServer来实现客户端与服务器并发连接非阻塞socket。
ThreadingTCPServer派生自ThreadingMixIn,主要实现核心的进程化合线程化功能。StreamRequestHandler主要用于用于TCP/UDP服务器的服务处理工具。
一、创建SocketServerTCP服务端
#创建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()
二、创建SocketServerTCP客户端
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()