不应该让服务端随着 并发的客户端数量增多,而无数起线程,应该用线程池,限制线程数量,控制最大并发数
io密集型程序,最大并发数是2
客户端
from socket import * client = socket(AF_INET, SOCK_STREAM) client.connect((‘127.0.0.1‘, 8080)) while True: msg = input(">>>:").strip() if not msg:break client.send(msg.encode("utf-8")) data = client.recv(1024) print(data.decode("utf-8")) client.close()
服务端
from socket import * from concurrent.futures import ThreadPoolExecutor def communicate(conn): ‘‘‘ 通信功能 ‘‘‘ while True: try: data = conn.recv(1024) if not data:break conn.send(data.upper()) except ConnectionResetError: break conn.close() def server(ip,port): ‘‘‘ 负责建立连接 accept‘‘‘ server = socket(AF_INET, SOCK_STREAM) server.bind((ip,port)) server.listen(5) while True: conn,addr = server.accept() pool.submit(communicate,conn) server.close() if __name__ == "__main__": pool = ThreadPoolExecutor(2) server(‘127.0.0.1‘, 8080)
原文:https://www.cnblogs.com/mingerlcm/p/11144804.html