本文整理汇总了Python中selectors.DefaultSelector.get_map方法的典型用法代码示例。如果您正苦于以下问题:Python DefaultSelector.get_map方法的具体用法?Python DefaultSelector.get_map怎么用?Python DefaultSelector.get_map使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类selectors.DefaultSelector
的用法示例。
在下文中一共展示了DefaultSelector.get_map方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from selectors import DefaultSelector [as 别名]
# 或者: from selectors.DefaultSelector import get_map [as 别名]
class EventLoop:
def __init__(self):
self.tasks = deque()
self.selector = DefaultSelector()
def run_until_complete(self, task):
self.tasks.append(task)
self.run()
def pause(self):
return "pause", None
def schedule(self, target):
return "schedule", target
def sock_accept(self, sock):
yield ("read", sock)
return sock.accept()
def sock_recv(self, sock):
yield ("read", sock)
return sock.recv(1024)
def sock_sendall(self, sock, data):
yield ("write", sock)
return sock.sendall(data)
def start_server(self, handler, host, port, backlog=0):
handler = partial(handler, self)
with socket.socket() as sock:
sock.bind((host, port))
sock.listen(backlog)
print("Listening on {}:{}".format(host, port))
while True:
conn, addr = yield from self.sock_accept(sock)
print("Accepted client from", addr)
yield self.schedule(handler(conn))
def run(self):
while self.tasks or self.selector.get_map():
for _ in range(len(self.tasks)):
try:
task = self.tasks.popleft()
tag, value = next(task)
if tag == "schedule":
self.tasks.append(value)
self.tasks.append(task)
elif tag == "read":
self.selector.register(value, EVENT_READ, data=task)
elif tag == "write":
self.selector.register(value, EVENT_WRITE, data=task)
elif tag == "pause":
self.tasks.append(task)
else:
raise ValueError("Incorrect tag")
except StopIteration:
continue
if self.selector.get_map():
for key, event in self.selector.select():
if event & EVENT_READ or event & EVENT_WRITE:
self.tasks.append(key.data)
self.selector.unregister(key.fileobj)