1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import socket 4 sk1 = socket.socket() 5 sk1.bind(('127.0.0.1',8001,)) 6 sk1.listen() 7 8 inputs = [sk1,] 9 outputs = [] 10 message_dict = {} 11 import select 12 while True: 13 # [sk1,sk2,sk3]select内部自动监听sk1,sk2,sk3,三个对象,一旦某个句柄发生变化(accept()) 14 # 如果有链接sk1 15 # r_list = [sk1,sk2] 16 r_list,w_list,e_list = select.select(inputs,outputs,inputs,1) 17 print('正在监听的socket对象%d' % len(inputs)) 18 print(r_list) 19 for sk1_or_conn in r_list: 20 # 每一个链接对象 21 if sk1_or_conn ==sk1: 22 # 表示有新用户链接 23 conn,adress = sk1_or_conn.accept() 24 inputs.append(conn) 25 message_dict[conn] = [] 26 else: 27 # 表示有老用户来链接 28 try: 29 data_bytes = sk1_or_conn.recv(1024) 30 except Exception as e: 31 else: 32 data_str = str(data_bytes, encoding='utf-8') 33 message_dict[sk1_or_conn].append(data_str) 34 outputs.append(sk1_or_conn) 35 #sk1_or_conn.sendall(bytes(data_str + '好', encoding='utf-8')) 36 for conn in w_list: 37 recv_str = message_dict[conn][0] 38 del message_dict[conn][0] 39 conn.sendall(bytes(recv_str + '好', encoding='utf-8')) 40 outputs.remove(conn) 41 for sk in e_list: 42 inputs.remove(sk)