1. 代码:
import socket
import selectors #IO多路复用的选择模块
epoll_selector = selectors.EpollSelector() 实例化一个和epoll通信的选择器
server = socket.socket()
server.bind(("127.0.0.1",8899))
server.listen(1000)
epoll_selector.register(server,selector.EVENT_READ,accept) 监听有无连接
def accept(server):
conn,addr = server.accept()
epoll_selector.register(conn,selector.EVENT_READ,myread) 监听有无数据传输
def myread(conn):
recv_data = conn.recv(1024)
if recv_data:
print(recv_data)
conn.send(recv_data)
else:
epoll_selector.unregister(conn) 关闭该监听
conn.close()
while True:
events = epoll_selector.select() 查询准备好的事件
for key,mask in events:
callback = key.data 取出回调函数
sock = key.fileobj 取出套接字
callback(sock)
图例: