當前位置: 首頁>>代碼示例>>Python>>正文


Python DefaultSelector.get_map方法代碼示例

本文整理匯總了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)
開發者ID:swarog46,項目名稱:Python,代碼行數:66,代碼來源:file_server.py


注:本文中的selectors.DefaultSelector.get_map方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。