socket :底层模块
socketserver: 基于socket完成的
处理并发的客户端请求
只针对服务器端的代码作出改变
server端代码示例:
import socketserver import time class MyServer(socketserver.BaseRequestHandler): def handle(self): ''' 一旦有某个客户端连接,就开始执行 handle方法 :return: None ''' conn = self.request # conn指代每个连接该服务器的客户端 while True: try: content = conn.recv(1024).decode('utf-8') print(content) conn.send(b'hi') time.sleep(0.5) except Exception as r: break # 开启服务器 server = socketserver.ThreadingTCPServer(('ip', port), MyServer) server.serve_forever()
client端代码示例:
import socket sk = socket.socket() sk.connect(('10.11.30.149', 9001)) while True: sk.send(b'hello') recv_msg = sk.recv(1024).decode('utf-8') print(recv_msg)