1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import socket 5 #創建一個socket對象 6 sk1 = socket.socket() 7 #綁定ip和埠 8 sk1.bind(('127.0.0.1', 8001)) ...
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import socket 5 #創建一個socket對象 6 sk1 = socket.socket() 7 #綁定ip和埠 8 sk1.bind(('127.0.0.1', 8001)) 9 #監聽 10 sk1.listen() 11 #定義一個字典存放客戶端發送的信息 12 message_dict = {} 13 #inputs用於存放socket對象 14 inputs = [sk1] 15 #哪一個客戶端發送信息就把哪一個客戶端的存放進output 16 output = [] 17 import select 18 while True: 19 r_list, w_list, e_list = select.select(inputs, output, inputs, 1) 20 print('正在監聽的socket%d' %len(inputs)) 21 print(r_list) 22 for sk_or_conn in r_list: 23 if sk_or_conn == sk1: 24 conn, address = sk_or_conn.accept() 25 inputs.append(conn) 26 message_dict[conn] = [] 27 else: 28 try: 29 data_bytes = sk_or_conn.recv(1024) 30 except Exception as ex: 31 inputs.remove(sk_or_conn) 32 else: 33 data_str = str(data_bytes, encoding='utf-8') 34 message_dict[sk_or_conn].append(data_str) 35 output.append(sk_or_conn) 36 for conn in w_list: 37 data_message = message_dict[sk_or_conn][0] 38 del message_dict[sk_or_conn][0] 39 conn.sendall(bytes(data_message + '好',encoding='utf-8')) 40 output.remove(conn)View Code