1 # 线程池实现并发服务器 2 from multiprocessing.pool import ThreadPool 3 import socket 4 5 6 class Server(object): 7 def __init__(self): 8 self.server = socket.socket() 9 self.server.bind(("0.0.0.0", 6868)) 10 self.server.listen() 11 12 def recv_and_response(self, cli): 13 while True: 14 data = cli[0].recv(1024) 15 if data == b"close": 16 cli[0].close() 17 break 18 else: 19 print("接收到来自{}的数据: {}".format(cli[1], data.decode())) 20 cli[0].send(data) 21 print("{}断开连接".format(cli[1])) 22 23 def run(self): 24 while True: 25 client = self.server.accept() 26 pool = ThreadPool(10) 27 pool.apply_async(self.recv_and_response, args=(client, )) 28 29 30 if __name__ == '__main__': 31 s = Server() 32 s.run()