gevent 實現單線程下的socket連接

經過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, timeclient = 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())
相關文章
相關標籤/搜索