selector 模块
Posted my-love-is-python
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了selector 模块相关的知识,希望对你有一定的参考价值。
selector 模块进行自动匹配,当是windows系统时,自动匹配select, linux系统时,自动匹配epoll,传输时会明确告诉内核响应服务器的地址,速度要更快
import
selectors
import
socket
sel
=
selectors.DefaultSelector()
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)
def
read(conn, mask):
data
=
conn.recv(
1000
)
# 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)
while
True
:
events
=
sel.select()
for
key, mask
in
events:
callback
=
key.data
callback(key.fileobj, mask)
以上是关于selector 模块的主要内容,如果未能解决你的问题,请参考以下文章
(转)python异步编程--回调模型(selectors模块)