http://www.cnblogs.com/alex3714/articles/5830365.html
并发处理
#!/usr/bin/env python# Author:Zhangmingdaimport socketserverclass Mytcphandler(socketserver.BaseRequestHandler): ''' 定义一个socketserver的handler处理类,必须继承socketserver.BaseRequestHandler ''' def handle(self): '''所有的与单个客户端的交互都在此方法''' print('定义自己的socketserver.子handler类hander方法') while True: try: print('客户端IP:{}端口:{}'.format(self.client_address[0], self.client_address[1])) print('等待接收数据...') self.data = self.request.recv(1024) print('收到数据:',self.data.decode()) self.request.sendall(self.data.decode().upper().encode()) except ConnectionResetError as e: print('连接出现错误/客户端已断开:%s'% e) breakif __name__ == "__main__": HOST,PORT = 'localhost',6969 print('开启服务,监听端口') server = socketserver.ForkingTCPServer((HOST,PORT),Mytcphandler) #多进程并发 # server = socketserver.ThreadingTCPServer((HOST,PORT),Mytcphandler)#多线程并发 server.serve_forever()
#!/usr/bin/env python# Author:Zhangmingda#!/usr/bin/env python# Author:Zhangmingdaimport socketprint('创建客户端实例')client = socket.socket()print('开始连接服务器')client.connect(('localhost',6969))while True: msg = input('>>>输入要发送的命令:') print('开始发送数据') client.send(msg.encode('utf-8')) #发送汉子,必须encode()成bytes类型数据进行传输 if msg == '断开': print('关闭数据连接') client.close() break print('开始接受数据') recv_data = client.recv(1024) print('返回数据:',recv_data.decode())