程序代码:
# '''基于Gevent的协程TCP并发实例,可以同时处理几万连接量
import gevent
from gevent import monkey
monkey.patch_all() #接管所有阻塞
from socket import *
ADDR = ('0.0.0.0',8888)
s = socket()
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
s.bind(ADDR)
s.listen(3)
def handle(c): # 循环收发客户端消息
while True:
data = c.recv(1024).decode()
if not data:
break
print(data)
c.send(b'OK')
while True:
c,addr = s.accept() # 只阻塞在接收连接函数
print('Connect from:',addr)
gevent.spawn(handle,c)