服务端
import socket
sk1 = socket.socket()
sk1.bind(('127.0.0.1',8001,))
sk1.listen() inputs = [sk1,]
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,[],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)#添加客户端文件句柄到列表
else:
# 表示有老用户来链接
try:
data_bytes = sk1_or_conn.recv(1024)
data_str = str(data_bytes,encoding='utf-8')
sk1_or_conn.sendall(bytes(data_str+'好',encoding='utf-8'))
except Exception as e:
inputs.remove(sk1_or_conn)
客户端
import socket
obj = socket.socket()
obj.connect(('127.0.0.1',8001,))
while True:
inp = input('请如入内容:')
obj.sendall(bytes(inp,encoding='utf-8'))
rec_bytes = obj.recv(1024)
rec_str = str(rec_bytes,encoding='utf-8')
print(rec_str)