服务端:
# ### 进程池实现socket连接服务器 from multiprocessing import Pool import socket,os sk = socket.socket() sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) sk.bind(("127.0.0.1",8080)) sk.listen() def talk(conn,addr): while True: msg = conn.recv(1024).decode("utf-8") if msg == "q": break print("{} {}>>>:{}".format(os.getpid(),addr[1],msg)) conn.close() if __name__ == "__main__": p = Pool(5) while True: conn,addr = sk.accept() p.apply_async(talk,args=(conn,addr)) p.close() p.join() sk.close()
客户端:
# ### 进程池实现socket连接服务器 import socket sk = socket.socket() sk.connect(("127.0.0.1",8080)) while True: msg = input("客户端>>>:") sk.send(msg.encode("utf-8")) if msg == "q": break sk.close()