单线程下支持并发(服务端):
1 from gevent import spawn,monkey;monkey.patch_all() 2 from socket import * 3 4 def server(ip,port): 5 server = socket(AF_INET, SOCK_STREAM) 6 server.bind((ip,port)) 7 server.listen(5) 8 9 while True: 10 conn, addr = server.accept() 11 print(addr) 12 # .... 13 # t=Thread(target=talk,args=(conn,add)) 14 # t.start() 15 spawn(talk,conn,addr) 16 17 def talk(conn,addr): 18 while True: 19 try: 20 data=conn.recv(1024) 21 if not data:break 22 conn.send(data.upper()) 23 except ConnectionResetError: 24 break 25 conn.close() 26 27 if __name__ == '__main__': 28 server('127.0.0.1',8080)
单线程下实现并发(客户端):
1 from socket import * 2 client = socket(AF_INET, SOCK_STREAM) 3 client.connect(('127.0.0.1',8080)) 4 5 while True: 6 client.send('hello'.encode('utf-8')) 7 data=client.recv(1024) 8 print(data.decode('utf-8'))