#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
sk1 = socket.socket()
sk1.bind(('127.0.0.1',8001,))
sk1.listen() inputs = [sk1,]
outputs = []
message_dict = {}
import select
while True:
# [sk1,sk2,sk3]select内部自动监听sk1,sk2,sk3,三个对象,一旦某个句柄发生变化(accept())
# 如果有链接sk1
# r_list = [sk1,sk2]
r_list,w_list,e_list = select.select(inputs,outputs,inputs,1)
print('正在监听的socket对象%d' % len(inputs))
print(r_list)
for sk1_or_conn in r_list:
# 每一个链接对象
if sk1_or_conn ==sk1:
# 表示有新用户链接
conn,adress = sk1_or_conn.accept()
inputs.append(conn)
message_dict[conn] = []
else:
# 表示有老用户来链接
try:
data_bytes = sk1_or_conn.recv(1024)
except Exception as e:
else:
data_str = str(data_bytes, encoding='utf-8')
message_dict[sk1_or_conn].append(data_str)
outputs.append(sk1_or_conn)
#sk1_or_conn.sendall(bytes(data_str + '好', encoding='utf-8'))
for conn in w_list:
recv_str = message_dict[conn][0]
del message_dict[conn][0]
conn.sendall(bytes(recv_str + '好', encoding='utf-8'))
outputs.remove(conn)
for sk in e_list:
inputs.remove(sk)