from gevent import monkey, spawn;monkey.patch_all()from socket import socket,AF_INET,SOCK_STREAM
from threading import Thread,current_thread
defcommunicat(conn):print("子线程: %s"% current_thread().getName())whileTrue:try:
data = conn.recv(1024)ifnot data:break
conn.send(data.upper())except ConnectionRefusedError:break
conn.close()defserver(ip, port):print("主线程: %s"% current_thread().getName())
s = socket(AF_INET, SOCK_STREAM)
s.bind((ip, port))
s.listen(5)while1:
conn, addr = s.accept()print(addr)# t = Thread(target=communicat, args=(conn,))# t.start()
spawn(communicat, conn)
s.close()if __name__ =="__main__":
g = spawn(server,"127.0.0.1",8081)
g.join()
client.py
from socket import socket,AF_INET,SOCK_STREAM
from threading import Thread, current_thread
defclient():
c = socket(AF_INET, SOCK_STREAM)
c.connect(("127.0.0.1",8081))while1:
msg ="%s say hello"% current_thread().getName()
c.send(msg.encode("utf-8"))
r = c.recv(1024)print(r.decode("utf-8"))
c.close()if __name__ =="__main__":for i inrange(500):
t = Thread(target=client)
t.start()