Python随心记--socketserver:实现并发
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python随心记--socketserver:实现并发相关的知识,希望对你有一定的参考价值。
#服务端
import socketserver class Myserver(socketserver.BaseRequestHandler): def handle(self): print(self.request) #conn 连接 print(self.client_address) #addr 地址 while True: try: data = self.request.recv(1024) #接收消息 if not data:break print(‘收到客户端的消息是‘,data) self.request.sendall(data.upper()) #发消息 except Exception as e: break; if __name__ == ‘__main__‘: s = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8080),Myserver) s.serve_forever()
客服端1
from socket import * import struct from functools import partial ip_port=(‘127.0.0.1‘,8080) back_log=5 buffer_size=1024 tcp_client=socket(AF_INET,SOCK_STREAM) tcp_client.connect(ip_port) while True: msg=input(‘>>: ‘).strip() if not msg:continue if msg == ‘quit‘:break tcp_client.send(msg.encode(‘utf-8‘)) data = tcp_client.recv(buffer_size) print(data) tcp_client.close()
客户端2
from socket import * import struct from functools import partial ip_port=(‘127.0.0.1‘,8080) back_log=5 buffer_size=1024 tcp_client=socket(AF_INET,SOCK_STREAM) tcp_client.connect(ip_port) while True: msg=input(‘>>: ‘).strip() if not msg:continue if msg == ‘quit‘:break tcp_client.send(msg.encode(‘utf-8‘)) data = tcp_client.recv(buffer_size) print(data) tcp_client.close()
以上是关于Python随心记--socketserver:实现并发的主要内容,如果未能解决你的问题,请参考以下文章