io多路复用(一)
sever端
1 import socket 2 sk1 = socket.socket() 3 sk1.bind(('127.0.0.1',8001,)) 4 sk1.listen() 5 6 sk2 = socket.socket() 7 sk2.bind(('127.0.0.1',8002,)) 8 sk2.listen() 9 10 sk3 = socket.socket() 11 sk3.bind(('127.0.0.1',8003,)) 12 sk3.listen() 13 inputs = [sk1,sk2,sk3] 14 import select 15 while True: 16 # [sk1,sk2,sk3]select内部自动监听sk1,sk2,sk3,三个对象,一旦某个句柄发生变化(accept()) 17 # 如果有链接sk1 18 # r_list = [sk1,sk2] 19 r_list,w_list,e_list = select.select(inputs,[],[],1) 20 for sk in r_list: 21 conn,adress = sk.accept() 22 conn.sendall(bytes('hello',encoding='utf-8')) 23 conn.close()
客户端,可同时连接多个客户端
1 import socket 2 obj = socket.socket() 3 obj.connect(('127.0.0.1',8001,)) 4 5 rec_bytes = obj.recv(1024) 6 rec_str = str(rec_bytes,encoding='utf-8') 7 print(rec_str) 8 obj.close()