Python 协程 socket
服务器端:
import socket
import gevent
from gevent import monkey
monkey.patch_all()
def handle_request(conn):
print("in the handle")
try :
while True:
data=conn.recv(1024)
print("recv:",data)
conn.send(data)
if not data:
conn.shutdown(socket.SHUT_WR)
except Exception as ex:
print(ex)
finally:
conn.close()
def server(port):
s=socket.socket()
s.bind(("localhost",port))
s.listen(500)
while True:
cli,addr=s.accept()
gevent.spawn(handle_request,cli)
if __name__ == "__main__":
server(9999)
客户端:
import socket
PORT = 9999
HOST = "localhost"
s = socket.socket()
s.connect((HOST,PORT))
while True:
data=input(">>:")
msg = bytes(data.encode("utf-8"))
s.send(msg)
data=s.recv(1024)
print("recieved",data.decode())
s.close()