Server:
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) the while True: Conn, addr = s.accept () # built connection Print (addr) # communications G = the spawn (Talk, Conn) # submit a coroutine task communication. A plurality of switching back and forth between the client # cutting very quickly, a plurality of clients in a timely manner in response S.CLOSE () IF the __name__ == ' __main__ ' : the spawn (Server, ' 127.0.0.1 ' , 8080 ). the Join () # Server (( '127.0.0.1', 8080)) and the above step # same effect
Client:
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('. 8-UTF ' )) IF the __name__ == ' __main__ ' : for I in Range (1000): # build server 500 communicates a threaded connection, corresponding to 500 concurrent client T = the Thread (target = Client) T. start ()