"""
io多路复用 select
select tcp 服务
"""
from socket import *
from select import *
s = socket()# 创建套接字,监听连接
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
s.bind(('0.0.0.0', 9999))
s.listen(5)
rlist = [s]
while True:
try:
rs, ws, xs = select(rlist,[], [])
except:
continue
for i in rs:
if i == s:
c, addr = i.accept()
rlist.append(c)
else:
data = i.recv(1024).decode()
if not data:
rlist.remove(i)
i.close()
else:
print(data)
i.send(b'thanks')
"""
io多路复用的实现 poll()
"""
from select import *
from socket import *
s = socket()# 创建套接字 io
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
s.bind(('0.0.0.0', 8888))
s.listen(5)
print('监控io')
fdmap = {s.fileno(): s}# 键值对保持文件描述符和io
p = poll()# 创建poll对象
p.register(s, POLLIN)# 关注io事件
while True:
events = p.poll()# 监控io事件,返回就绪io事件列表,内部元素是(io事件文件符,类型)构成的元组
for fd, event in events:
if fdmap[fd] == s:
c, addr = fdmap[fd].accept()
p.register(c, POLLIN | POLLERR)
fdmap[c.fileno()] = c
elif event & POLLIN:
data = fdmap[fd].recv(1024).decode()
if not data:
p.unregister(fd)
del fdmap[fd]
else:
print(data)
fdmap[fd].send(b'ok')