通过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())










posted on 2018-06-10 22:35  python我的最爱  阅读(273)  评论(0编辑  收藏  举报