python sockeserver 實現併發
server 端:
import socketserver
class MyServer(socketserver.BaseRequestHandler): def handle(self): print('conn is:',self.request) print('addr is:',self.client_address)
while True: try: data=self.request.recv(1024)
if not data:break
print('收到客戶端訊息:',data)
self.request.sendall(data.upper()) except Exception as e: print(e) break
if __name__=='__main__': s = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer) s.serve_forever()
client 端:
from socket import * ip_port=('127.0.0.1',8080) back_log=5 buffer_size=1024
tcp_clinet=socket(AF_INET,SOCK_STREAM) tcp_clinet.connect(ip_port)
while True: msg=input('>>:').strip() if not msg:continue if msg == 'quit':break
tcp_clinet.send(msg.encode('utf-8'))
data=tcp_clinet.recv(buffer_size) print('收到服務端發來的訊息:',data.decode('utf-8'))
tcp_clinet.close()