IO多路复用,实现多线程监听

服务端
import socket sk1 = socket.socket()
sk1.bind(('127.0.0.1',8001))
sk1.listen() sk2 = socket.socket()
sk2.bind(('127.0.0.1',8002))
sk2.listen() sk3 = socket.socket()
sk3.bind(('127.0.0.1',8003))
sk3.listen() inp = [sk1,]
import select while True:
print(len(inp))
#r_list 接收inp参数 如果有用户来链接 它就会感知到,
#w_list 可以写固定句柄 进行监听 如果 [sk1,sk3]
#e_list 监听发生错误的句柄,如果有把就把它移除掉, 如下面for循环
r_list, w_list, e_list= select.select(inp,[],[],1)
for i in r_list:
# print(i,'\n',sk1.accept())
if i == sk1:
# print(i.accept(),'\n',sk1.accept())
conn,address = i.accept()
inp.append(conn)
print(inp)
else:
try:
str(conn.recv(1024),encoding='utf-8')
conn.sendall(bytes('hello',encoding='utf-8'))
except Exception as e:
inp.remove(i)
客户端
import socket obj = socket.socket()
obj.connect(('127.0.0.1',8001))
inp = input('')
obj.sendall(bytes(inp,encoding='utf-8'))
r = str(obj.recv(1024),encoding='utf-8')
print(r)
上一篇:IPC机制


下一篇:设备树-节点