pool 进程池实现 socket 并发连接

服务端:

# ### 进程池实现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()

 

上一篇:前端学习日记 (一)


下一篇:TCP输出 之 tcp_write_xmit