Python 官方文档:入门教程 => 点击学习
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: Changhua Gong import selectors import Socket sel = selecto
#!/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为文件句柄
--结束END--
本文标题: Python selectors
本文链接: https://lsjlt.com/news/186714.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0