设置池.Gevent中的池无效

时间:2018-12-17 09:56:25

标签: python gevent

我尝试在gevent模块中测试池方法,所以编写如下代码:

# 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)

程序正常运行,没有任何错误。但是我认为服务器的代码应该收到错误,因为我在其中设置了pool = pool.Pool(2)。   我尝试设置pool.Pool(1)并打开运行在一起的多客户端,但结果没有变化。

0 个答案:

没有答案