Python隨心記--socketserver:實現並發
阿新 • • 發佈:2019-01-12
handler ddr utf-8 col ESS pan back quit and
#服務端
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:breakprint(‘收到客戶端的消息是‘,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 * importstruct 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:實現並發