協(xié)程雖然是輕量級的線程,但到達一定數(shù)量后,仍然會造成服務器崩潰出錯。最好的方法通過限制協(xié)程并發(fā)數(shù)量來解決此類問題。
server代碼:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Cain
# @Email : 771535427@qq.com
# @Filename : gevnt_sockserver.py
# @Last modified : 2017-11-24 16:31
# @Description :
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()運行協(xié)程
def handle_request(conn):
try:
data = conn.recv(1024)
print("recv:", data)
data = 'From SockeServer:192.168.88.118---%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(5) #限制并發(fā)協(xié)程數(shù)量5
server(8888, pool)
client(通過gevent模擬并發(fā)數(shù)量):
import socket
import gevent
from gevent import socket, monkey
from gevent.pool import Pool
import time
monkey.patch_all()
HOST = '192.168.88.118'
PORT = 8888
def sockclient(i):
#time.sleep(2)
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(5)
threads = [pool.spawn(sockclient, i) for i in range(2000)]
gevent.joinall(threads)
由于服務器限制連接并發(fā)數(shù)量;所以客戶端同時并發(fā)連接數(shù)超過服務器端并發(fā)數(shù)量,就會引發(fā)連接錯誤信息:
Exception in thread Thread-849:
Traceback (most recent call last):
File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "E:/chengd/python/python3/matp/die/geven_sockclient.py", line 26, in sockclient
data = s.recv(1024)
ConnectionResetError: [WinError 10054] 遠程主機強迫關(guān)閉了一個現(xiàn)有的連接。
到此這篇關(guān)于python3通過gevent.pool限制協(xié)程并發(fā)數(shù)量的文章就介紹到這了,更多相關(guān)python3協(xié)程并發(fā)數(shù)量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python gevent協(xié)程切換實現(xiàn)詳解
- python 協(xié)程 gevent原理與用法分析
- Python協(xié)程操作之gevent(yield阻塞,greenlet),協(xié)程實現(xiàn)多任務(有規(guī)律的交替協(xié)作執(zhí)行)用法詳解
- 簡單了解python gevent 協(xié)程使用及作用
- 詳解python之協(xié)程gevent模塊