chouliqingke 2019-12-14
利用socketserver模块很容易实现并发功能,下面的server.py和client.py程序实现了这一功能.
#server.pyimport socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): while True: conn = self.request while True: data = conn.recv(1024) if str(data,‘utf8‘) == ‘q‘: break print(str(data,‘utf8‘)) inp = input(‘>>>‘) conn.send(bytes(inp,‘utf8‘)) conn.close() if __name__ == ‘__main__‘: server = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8000),MyServer) server.serve_forever()
#client.py import socket sk = socket.socket() address = (‘127.0.0.1‘,8000) sk.connect(address) while True: inp = input(‘>>>‘) if inp == ‘q‘: print(‘Bye-bye‘) break sk.send(bytes(inp,‘utf8‘)) data = sk.recv(1024) print(str(data,‘utf8‘))