进程池线程池并发服务器
# -*- coding: utf-8 -*- """ 进程池和线程池实现并发 socket编程共两个阻塞的地方,生成对等套接字和接收数据 1.将生成对等套接字给进程池 2.将接收数据交给线程池(进程池中) """ from multiprocessing.pool import ThreadPool from multiprocessing import Pool, cpu_count # 获取机器cpu数量 import socket def process_worker(server): thread_pool = ThreadPool(4) while True: conn, addr = server.accept() # 对等连接套接字 thread_pool.apply_async(thread_worker, args=(conn, )) # thread_pool.join() def thread_worker(conn): while True: recv_data = conn.recv(1024) if recv_data: print(recv_data.decode()) conn.send(recv_data) else: conn.close() break def main(): server = socket.socket() server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 释放端口 server.bind(("", 8000)) server.listen(1000) # 监听套接字 pool = Pool(cpu_count()) # 生成进程池 for i in range(cpu_count()): pool.apply_async(process_worker, args=(server, )) pool.close() print('apply is starting!!!') pool.join() if __name__ == "__main__": main()
奇怪的是在windows下运行出错,在linux没出错。
recv_data = client.recv(1024) # 该处出错
ConnectionAbortedError: [WinError 10053] 你的主机中的软件中止了一个已建立的连接。