这是一个创建于 2172 天前的主题,其中的信息可能已经有所发展或是发生改变。
--server 端
import sys
import socket
import time
import gevent
from gevent import socket,monkey,pool #导入 pool
monkey.patch_all()
def server(port, pool):
s = socket.socket()
s.bind(('0.0.0.0', port))
s.listen()
while True:
cli, addr = s.accept()
#print("Welcome %s to SocketServer" % str(addr[0]))
pool.spawn(handle_request, cli) #通过 pool.spawn()运行协程
def handle_request(conn):
try:
data = conn.recv(1024)
print("recv:", data)
data = 'From SockeServer:---%s' % data.decode("utf8")
conn.sendall(bytes(data, encoding="utf8"))
if not data:
conn.shutdown(socket.SHUT_WR)
except Exception as ex:
print(ex)
finally:
conn.close()
if __name__ == '__main__':
pool = pool.Pool(2) #限制并发协程数量 5
server(8888, pool)
--client 端
import socket
import gevent
from gevent import socket, monkey
from gevent.pool import Pool
import time
monkey.patch_all()
HOST = '192.168.2.202'
PORT = 8888
def sockclient(i):
s = socket.socket()
s.connect((HOST, PORT))
#print(gevent.getcurrent())
msg = bytes(("This is gevent: %s" % i),encoding="utf8")
s.sendall(msg)
data = s.recv(1024)
print("Received", data.decode())
s.close()
pool = Pool(50)
threads = [pool.spawn(sockclient, i) for i in range(2000)]
gevent.joinall(threads)
按道理说我在服务端设置协程池的数量为 2, 而客户端一次性向服务端发 50 个,服务端应该报错才对, 可是服务端并没有报错, 而且即使我开 3 个客户端同时连接服务端程序依然运行正常, 这是怎么原因? 服务端的 pool.Pool(2)完全没有作用呀.
|
|
1
chen222246lei 2018-12-20 09:23:22 +08:00
哪位大佬帮忙看看是怎么回事? 我不信没人懂.
|