python3 进程池版的socket并发聊天
2020-12-02 06:02
标签:coding strong int enc syn tpi class pytho while tcp_client.py 发现:并发开启多个客户端,服务端同一时间只有4个不同的pid,只能结束一个客户端,另外一个客户端才会进来. python3 进程池版的socket并发聊天 标签:coding strong int enc syn tpi class pytho while 原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10986698.htmlPool内的进程数默认是cpu核数,假设为4(查看方法os.cpu_count())
开启6个客户端,会发现2个客户端处于等待状态
在每个进程内查看pid,会发现pid使用为4个,即多个客户端公用4个进程
tcp_server.py# coding:utf-8
import os
import socket
from multiprocessing import Pool
def tcpserver(conn):
while 1:
from_client_msg = conn.recv(1024)
if not from_client_msg: break
print("[%s]来自客户端的消息:" % os.getpid(), from_client_msg)
conn.send(from_client_msg.upper())
if __name__ == ‘__main__‘:
server = socket.socket()
ip_port = ("127.0.0.1", 8001)
server.bind(ip_port)
server.listen(5)
pool = Pool(os.cpu_count())
print("pool count:", os.cpu_count())
while 1:
conn, addr = server.accept()
res = pool.apply_async(tcpserver, args=(conn,))
pool.close()
pool.join()
# coding:utf-8
import socket
if __name__ == ‘__main__‘:
client = socket.socket()
ip_port = ("127.0.0.1", 8001)
client.connect(ip_port)
while 1:
inp = input(">>>>:").strip()
if not inp: continue
client.send(inp.encode("utf-8"))
from_server_msg = client.recv(1024)
print("来自服务端的消息:", from_server_msg)
上一篇:STA 108B Spring Quarter 2019
下一篇:java多态
文章标题:python3 进程池版的socket并发聊天
文章链接:http://soscw.com/index.php/essay/23203.html