io多路复用(二)
服务端
1 import socket 2 sk1 = socket.socket() 3 sk1.bind(('127.0.0.1',8001,)) 4 sk1.listen() 5 6 inputs = [sk1,] 7 import select 8 while True: 9 # [sk1,sk2,sk3]select内部自动监听sk1,sk2,sk3,三个对象,一旦某个句柄发生变化(accept()) 10 # 如果有链接sk1 11 # r_list = [sk1,sk2] 12 r_list,w_list,e_list = select.select(inputs,[],inputs,1) 13 print('正在监听的socket对象%d' % len(inputs)) 14 print(r_list) 15 for sk1_or_conn in r_list: 16 # 每一个链接对象 17 if sk1_or_conn ==sk1: 18 # 表示有新用户链接 19 conn,adress = sk1_or_conn.accept() 20 inputs.append(conn)#添加客户端文件句柄到列表 21 else: 22 # 表示有老用户来链接 23 try: 24 data_bytes = sk1_or_conn.recv(1024) 25 data_str = str(data_bytes,encoding='utf-8') 26 sk1_or_conn.sendall(bytes(data_str+'好',encoding='utf-8')) 27 except Exception as e: 28 inputs.remove(sk1_or_conn)
客户端
1 import socket 2 obj = socket.socket() 3 obj.connect(('127.0.0.1',8001,)) 4 while True: 5 inp = input('请如入内容:') 6 obj.sendall(bytes(inp,encoding='utf-8')) 7 rec_bytes = obj.recv(1024) 8 rec_str = str(rec_bytes,encoding='utf-8') 9 print(rec_str)