Python selectors
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: Changhua Gong
import selectors
import Socket
sel = selectors.DefaultSelector()
'''selectors根据系统自动select或epoll'''
def accept(sock, mask):
conn, addr = sock.accept() # Should be ready
print('accepted', conn, 'from', addr)
conn.setblocking(False) # 设置连接不阻塞
sel.reGISter(conn, selectors.EVENT_READ, read) # 新连接注册read回调函数
def read(conn, mask):
data = conn.recv(1024) # Should be ready
if data:
print('echoing', repr(data), 'to', conn)
conn.send(data) # Hope it won't block
else:
print('closing', conn)
sel.unregister(conn)
conn.close()
sock = socket.socket()
sock.bind(('localhost', 10000))
sock.listen(100)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept) # 注册sock,有连接进来则调用accept
while True:
events = sel.select() # 默认阻塞,有活动连接就返回活动的连接列表
for key, mask in events:
callback = key.data # accept的内存地址或read的内存地址,即等于read或accept函数
callback(key.fileobj, mask) # 调用对应的回调函数,key.fileobj为文件句柄
相关文章