Python selectors
selectors 封装了 select 和 epoll,默认使用 epoll,如果无法使用 epoll 就换成 select
select 和 epoll 为 IO多路复用的方式 <- 点击查看
示例:
socket server
import selectors
import socket
sel = selectors.DefaultSelector()
def accept(sock, mask):
conn, addr = sock.accept()
print('accepted', conn, 'from', addr)
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read) # 注册连接
def read(conn, mask):
data = conn.recv(1024)
if data:
print('echoing', repr(data), 'to', conn)
conn.send(data)
else:
print('closing', conn)
sel.unregister(conn)
conn.close()
sock = socket.socket()
sock.bind(('localhost', 8001))
sock.listen(100)
sock.setblocking(False) # 设置非阻塞
sel.register(sock, selectors.EVENT_READ, accept) # 注册连接
while True:
events = sel.select()
for key, mask in events:
callback = key.data # 设置回调函数
callback(key.fileobj, mask) # 执行回调函数
socket client
import socket
HOST = 'localhost'
PORT = 8001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
msg = bytes(input(">>:"), encoding="utf8")
s.sendall(msg)
data = s.recv(1024)
print('Received', repr(data))
当一个新连接进来时调用 accept,当一个已知连接发送数据时调用 read