gevent 实现单线程下的socket链接

时间:2021-12-04 15:01:05
通过gevent实现socket的多并发

server 端:

import gevent
from gevent import socket, monkey monkey.patch_all() #进行IO标记 def server(port):
s = socket.socket()
s.bind(('localhost', port))
s.listen()
while True:
conn, addr = s.accept()
gevent.spawn(handle, conn) #一接收信号就进行IO切换 def handle(conn):
try:
data = conn.recv(1024)
print(data)
conn.send(data)
if not data:
conn.shutdown(socket.SHUT_WR) #如果没有数据就关掉socket
except exception as ex:
print(ex)
finally:
conn.close() if __name__=='__main__':
server(8000) client 端:
import socket, time

client = socket.socket()
client.connect(('localhost', 6000))
while True:
data = input('>>')
client.send(data.encode('utf-8'))
if not data:
break d = client.recv(1024)
print('recv:', d.decode())