服务端:
from gevent import monkey,spawn;monkey.patch_all() from threading import Thread from socket import * def talk(conn): #跟建好的连接进行通讯 while True: try: data=conn.recv(1024) if not data:break conn.send(data.upper()) except ConnectionResetError: break conn.close() def server(ip,port,backlog=5): s = socket() s.bind((ip,port)) s.listen(backlog) while True: conn, addr = s.accept() #建连接 print(addr) # 通信 g=spawn(talk,conn) #提交一个协程任务,进行通讯。在多个客户端之间来回切换 #切的速度非常快,多个客户端都得到及时响应 s.close() if __name__ == '__main__': spawn(server,'127.0.0.1',8080).join() # server(('127.0.0.1',8080)) #和上面一步效果相同
客户端:
from threading import Thread,current_thread from socket import * import os def client(): client = socket() client.connect(('127.0.0.1', 8080)) while True: data = '%s hello' % current_thread().name client.send(data.encode('utf-8')) res = client.recv(1024) print(res.decode('utf-8')) if __name__ == '__main__': for i in range(1000): #建500个线程连接服务端进行通信,相当于并发500个客户端 t=Thread(target=client) t.start()