from gevent Import Monkey; monkey.patch_all () from socket Import * from gevent Import spawn # before importing spawn must pass Monkey # both a io intensive tasks DEF Comun (conn): the while True: # links circulating the try : data = conn.recv(1024) if len(data) == 0: break conn.send(data.upper()) except ConnectionResetError: break conn.close() def server(ip,port,backlog=5): server = socket (AF_INET, SOCK_STREAM) server.bind((ip,port)) server.listen(backlog) the while True: # link cycle conn, client_addr = server.accept () Print (client_addr) # Communication spawn (comun, conn) if __name__ == '__main__': g1=spawn(server,'127.0.0.1',8080) g1.join()
from threading import Thread,current_thread #开线程 from socket import * def client(): client = socket (AF_INET, SOCK_STREAM) client.connect(('127.0.0.1',8080)) n=0 while True: msg='%s say hello %s' %(current_thread().name,n) n+=1 client.send(msg.encode('utf-8')) data=client.recv(1024) print(data.decode('utf-8')) if __name__ == '__main__': for i in range(500): t=Thread(target=client) t.start()
Realized withstand 500 concurrent amount in a single thread