#使用池来实现并发服务器
import socket
from multiprocessing import cpu_count,Pool
from multiprocessing.pool import ThreadPool
server=socket.socket()
server.bind(('0.0.0.0',8080))
server.listen(1000)
def work_process(server):#处理server的进程
thread_pool=ThreadPool(cpu_count()) #如果不想用线程池的话,可以直接用普通线程
while True:
connection,remote_address=server.accept()
thread_pool.apply_async(worker_thread,args=(connection,))
def worker_thread(connection):
while True:
recv_data=connection.recv(1000)
if recv_data:
print(recv_data.decode('utf-8'))
connection.send(recv_data)
else:
connection.close()
break
n=cpu_count() #获取cpu个数
pool=Pool(n)
for i in range(2):
pool.apply_async(work_process,args=(server,))
pool.close()
pool.join()