socket 进程池
import socket from multiprocessing import Pool import os server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) server.bind(('127.0.0.1',8080)) server.listen(5) def talk(conn,addr): print('进程pid:%s'%os.getpid()) while True: try: msg=conn.recv(1024) if not msg:break conn.send(msg.upper()) except Exception: break if __name__=='__main__': p=Pool(os.cpu_count()) #4 ,创建4个进程,以后只用这四个进程执行 while True: conn,addr=server.accept() p.apply_async(talk,args=(conn,addr)) #异步调用,4个进程同时启动,当其中一个执行完后,这个进程才能执行其他的 p.close(), p.join()
# p.apply(talk,args=(conn,addr))#同步调用,一个进程执行完一个程序后,下一个进程才能执行下一个程序
import socket client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(('127.0.0.1',8080)) while True: msg=input('>>') if not msg:continue client.send(msg.encode('utf-8')) msg=client.recv(1024) print(msg.decode('utf-8'))