1 #通过gevent实现单线程下的多socket并发 服务器 2 3 4 #server side 5 import sys 6 import socket 7 import time 8 import gevent 9 10 from gevent import socket,monkey 11 monkey.patch_all() 12 13 14 def server(port): 15 s = socket.socket() 16 s.bind(('0.0.0.0', port)) 17 s.listen(500) 18 while True: 19 cli, addr = s.accept() 20 gevent.spawn(handle_request, cli) 21 22 23 24 def handle_request(conn): 25 try: 26 while True: 27 data = conn.recv(1024) 28 print("recv:", data) 29 conn.send(data) 30 if not data: 31 conn.shutdown(socket.SHUT_WR) 32 33 except Exception as ex: 34 print(ex) 35 finally: 36 conn.close() 37 if __name__ == '__main__': 38 server(8001)
1 #通过gevent实现单线程下的多socket并发 客户端 2 3 import socket 4 5 HOST = 'localhost' # The remote host 6 PORT = 8001 # The same port as used by the server 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 s.connect((HOST, PORT)) 9 while True: 10 msg = bytes(input(">>:"),encoding="utf8") 11 s.sendall(msg) 12 data = s.recv(1024) 13 #print(data) 14 15 print('Received', repr(data)) 16 s.close()
1 #通过gevent实现单线程下的多socket并发 客户端#并发多个sock连接 2 3 import socket 4 import threading 5 6 def sock_conn(): 7 8 client = socket.socket() 9 10 client.connect(("localhost",8001)) 11 count = 0 12 while True: 13 #msg = input(">>:").strip() 14 #if len(msg) == 0:continue 15 client.send( ("hello %s" %count).encode("utf-8")) 16 17 data = client.recv(1024) 18 19 print("[%s]recv from server:" % threading.get_ident(),data.decode()) #结果 20 count +=1 21 client.close() 22 23 24 for i in range(50): 25 t = threading.Thread(target=sock_conn) 26 t.start()