python之selectors
程序员文章站
2022-03-06 10:15:44
selectors是select模块的包装器,ptython文档建议大部分情况使用selectors而不是直接使用selectors ......
selectors是select模块的包装器,ptython文档建议大部分情况使用selectors而不是直接使用selectors
样例代码如下
# -*- coding: utf-8 -*-
__author__ = 'fc'
import selectors
import socket
import time
def accept(sock:socket.socket, mask):
conn, addr = sock.accept()
print('client', addr, 'connected')
conn.setblocking(false)
sel.register(conn, selectors.event_read, oper)
def oper(sock:socket.socket, mask):
if selectors.event_read & mask:
print('ready to read')
data = sock.recv(1024)
if not data:
print('client', sock.getpeername(), 'disconnnected')
sel.unregister(sock)
sock.close()
else:
print('received: ', data)
sel.modify(sock, selectors.event_write, oper)
elif selectors.event_write & mask:
print('ready to write')
msg = b'hello, friend'
sock.send(msg)
print('send: ', msg)
sel.modify(sock, selectors.event_read, oper)
sel = selectors.defaultselector()
print(sel)
sock = socket.socket(socket.af_inet, socket.sock_stream, 0)
sock.bind(('', 60001))
sock.listen(5)
sock.setblocking(false)
sel.register(sock, selectors.event_read, accept)
while true:
events = sel.select(10)
if not events:
print('timeout', time.strftime('%y-%m-%d %h:%m:%s'))
for key, mask in events:
callback = key.data
callback(key.fileobj, mask)