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


Python asyncio.Protocol方法代碼示例

本文整理匯總了Python中asyncio.Protocol方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.Protocol方法的具體用法?Python asyncio.Protocol怎麽用?Python asyncio.Protocol使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在asyncio的用法示例。


在下文中一共展示了asyncio.Protocol方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: datagram_received

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def datagram_received(self, data, addr):
        """
        Opens a read or write connection to remote host by scheduling
        an asyncio.Protocol.
        """
        logger.debug('received: {}'.format(data.decode()))

        first_packet = self.packet_factory.from_bytes(data)
        protocol = self.select_protocol(first_packet)
        file_handler_cls = self.select_file_handler(first_packet)

        connect = self.loop.create_datagram_endpoint(
            lambda: protocol(data, file_handler_cls, addr, self.extra_opts),
            local_addr=(self.host_interface,
                        0, ))

        self.loop.create_task(connect) 
開發者ID:sirMackk,項目名稱:py3tftp,代碼行數:19,代碼來源:protocols.py

示例2: __aenter__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def __aenter__(self):
        transports = self._transports
        write_buff = self._write_buff

        class SocksPrimitiveProtocol(asyncio.Protocol):
            _transport = None

            def connection_made(self, transport):
                self._transport = transport
                transports.append(transport)

            def data_received(self, data):
                self._transport.write(write_buff)

        def factory():
            return SocksPrimitiveProtocol()

        self._srv = await self._loop.create_server(
            factory, '127.0.0.1', self.port)

        return self 
開發者ID:nibrag,項目名稱:aiosocks,代碼行數:23,代碼來源:test_utils.py

示例3: connection_lost

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def connection_lost(self, exc):
        """Reestablish the connection to the transport.

        Called when asyncio.Protocol loses the network connection.
        """
        if exc is None:
            _LOGGER.warning("End of file received from Insteon Modem")
        else:
            _LOGGER.warning("Lost connection to Insteon Modem: %s", exc)

        self.transport = None
        asyncio.ensure_future(self.pause_writing(), loop=self.loop)

        if self._connection_lost_callback:
            self._connection_lost_callback()

    # Methods used to trigger callbacks for specific events 
開發者ID:nugget,項目名稱:python-insteonplm,代碼行數:19,代碼來源:plm.py

示例4: connection_made

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def connection_made(self, transport):
        """Start the PLM connection process.

        Called when asyncio.Protocol establishes the network connection.
        """
        _LOGGER.info("Connection established to PLM")
        self.transport = transport

        self._restart_writer = True
        self.restart_writing()

        # Testing to see if this fixes the 2413S issue
        self.transport.serial.timeout = 1
        self.transport.serial.write_timeout = 1
        self.transport.set_write_buffer_limits(128)
        # limit = self.transport.get_write_buffer_size()
        # _LOGGER.debug('Write buffer size is %d', limit)
        if self._aldb.status != ALDBStatus.LOADED:
            asyncio.ensure_future(self._setup_devices(), loop=self._loop) 
開發者ID:nugget,項目名稱:python-insteonplm,代碼行數:21,代碼來源:plm.py

示例5: test_make_ssl_transport

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def test_make_ssl_transport(self):
        m = mock.Mock()
        self.loop.add_reader = mock.Mock()
        self.loop.add_reader._is_coroutine = False
        self.loop.add_writer = mock.Mock()
        self.loop.remove_reader = mock.Mock()
        self.loop.remove_writer = mock.Mock()
        waiter = asyncio.Future(loop=self.loop)
        with test_utils.disable_logger():
            transport = self.loop._make_ssl_transport(
                m, asyncio.Protocol(), m, waiter)
            # execute the handshake while the logger is disabled
            # to ignore SSL handshake failure
            test_utils.run_briefly(self.loop)

        # Sanity check
        class_name = transport.__class__.__name__
        self.assertIn("ssl", class_name.lower())
        self.assertIn("transport", class_name.lower())

        transport.close()
        # execute pending callbacks to close the socket transport
        test_utils.run_briefly(self.loop) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:25,代碼來源:test_selector_events.py

示例6: test_empty

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def test_empty(self):
        f = mock.Mock()
        p = asyncio.Protocol()
        self.assertIsNone(p.connection_made(f))
        self.assertIsNone(p.connection_lost(f))
        self.assertIsNone(p.data_received(f))
        self.assertIsNone(p.eof_received())

        dp = asyncio.DatagramProtocol()
        self.assertIsNone(dp.connection_made(f))
        self.assertIsNone(dp.connection_lost(f))
        self.assertIsNone(dp.error_received(f))
        self.assertIsNone(dp.datagram_received(f, f))

        sp = asyncio.SubprocessProtocol()
        self.assertIsNone(sp.connection_made(f))
        self.assertIsNone(sp.connection_lost(f))
        self.assertIsNone(sp.pipe_data_received(1, f))
        self.assertIsNone(sp.pipe_connection_lost(1, f))
        self.assertIsNone(sp.process_exited()) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:22,代碼來源:test_events.py

示例7: make_console

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def make_console(bot):
    class Console(asyncio.Protocol):
        def connection_made(self, transport):
            self.transport = transport
            self.transport.write(b'>>> ')
            self.bot = bot

        def data_received(self, data):
            """
            Called when some data is received.
            The argument is a bytes object.
            """
            if data == b'\xff\xf4\xff\xfd\x06':
                self.transport.close()
                return
            message = data.decode()
            resp = str(eval(message)) + "\n>>> "
            self.transport.write(resp.encode('utf-8'))
    return Console 
開發者ID:cookkkie,項目名稱:mee6,代碼行數:21,代碼來源:backdoor.py

示例8: connect

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def connect(self) -> None:
        """Open a connection to the defined server."""
        def protocol_factory() -> Protocol:
            return Protocol(client=self)

        _, protocol = await self.loop.create_connection(
            protocol_factory,
            host=self.host,
            port=self.port,
            ssl=self.ssl
        )  # type: Tuple[Any, Any]
        if self.protocol:
            self.protocol.close()
        self.protocol = protocol
        # TODO: Delete the following code line. It is currently kept in order
        # to not break the current existing codebase. Removing it requires a
        # heavy change in the test codebase.
        protocol.client = self
        self.trigger("client_connect") 
開發者ID:numberoverzero,項目名稱:bottom,代碼行數:21,代碼來源:client.py

示例9: __init__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def __init__(self, protocol_cls, loop=None, max_workers=2,
                 sync_kind=TextDocumentSyncKind.INCREMENTAL):
        if not issubclass(protocol_cls, asyncio.Protocol):
            raise TypeError('Protocol class should be subclass of asyncio.Protocol')

        self._max_workers = max_workers
        self._server = None
        self._stop_event = None
        self._thread_pool = None
        self._thread_pool_executor = None
        self.sync_kind = sync_kind

        if IS_WIN:
            asyncio.set_event_loop(asyncio.ProactorEventLoop())
        else:
            asyncio.set_event_loop(asyncio.SelectorEventLoop())

        self.loop = loop or asyncio.get_event_loop()

        try:
            asyncio.get_child_watcher().attach_loop(self.loop)
        except NotImplementedError:
            pass

        self.lsp = protocol_cls(self) 
開發者ID:openlawlibrary,項目名稱:pygls,代碼行數:27,代碼來源:server.py

示例10: task

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def task():
    rfd, wfd = os.pipe()
    args = [sys.executable, '-c', code, str(rfd)]
    proc = yield from asyncio.create_subprocess_exec(
                          *args,
                          pass_fds={rfd},
                          stdout=subprocess.PIPE)

    pipe = open(wfd, 'wb', 0)
    transport, _ = yield from loop.connect_write_pipe(asyncio.Protocol,
                                                      pipe)
    transport.write(b'data')

    stdout, stderr = yield from proc.communicate()
    print("stdout = %r" % stdout.decode())
    transport.close() 
開發者ID:hhstore,項目名稱:annotated-py-projects,代碼行數:18,代碼來源:subprocess_attach_write_pipe.py

示例11: setUp

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def setUp(self):
        self.loop = self.new_test_loop()
        self.protocol = test_utils.make_test_protocol(asyncio.Protocol)
        self.pipe = mock.Mock(spec_set=io.RawIOBase)
        self.pipe.fileno.return_value = 5

        blocking_patcher = mock.patch('asyncio.unix_events._set_nonblocking')
        blocking_patcher.start()
        self.addCleanup(blocking_patcher.stop)

        fstat_patcher = mock.patch('os.fstat')
        m_fstat = fstat_patcher.start()
        st = mock.Mock()
        st.st_mode = stat.S_IFIFO
        m_fstat.return_value = st
        self.addCleanup(fstat_patcher.stop) 
開發者ID:hhstore,項目名稱:annotated-py-projects,代碼行數:18,代碼來源:test_unix_events.py

示例12: start_reading_pty

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def start_reading_pty(protocol, pty_fd):
    """
    Make asyncio to read file descriptor of Pty

    :param protocol: protocol of subprocess speaking via Pty
    :param pty_fd: file descriptor of Pty (dialog with subprocess goes that way)
    :return:
    """
    loop, its_new = thread_secure_get_event_loop()

    # Create Protocol classes
    class PtyFdProtocol(asyncio.Protocol):
        def connection_made(self, transport):
            if hasattr(protocol, 'on_pty_open'):
                protocol.on_pty_open()

        def data_received(self, data, recv_time):
            if hasattr(protocol, 'data_received'):
                protocol.data_received(data)

        def connection_lost(self, exc):
            if hasattr(protocol, 'on_pty_close'):
                protocol.on_pty_close(exc)

    # Add the pty's to the read loop
    # Also store the transport, protocol tuple for each call to
    # connect_read_pipe, to prevent the destruction of the protocol
    # class instance, otherwise no data is received.
    fd_transport, fd_protocol = await loop.connect_read_pipe(PtyFdProtocol, os.fdopen(pty_fd, 'rb', 0))
    protocol.pty_fd_transport = fd_transport
    protocol.pty_fd_protocol = fd_protocol 
開發者ID:nokia,項目名稱:moler,代碼行數:33,代碼來源:terminal.py

示例13: test_base_negotiate_with_app_proto

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def test_base_negotiate_with_app_proto(loop):
    waiter = asyncio.Future(loop=loop)
    proto = make_base(loop, waiter=waiter,
                      ap_factory=lambda: asyncio.Protocol())
    proto.socks_request = make_mocked_coro((None, None))

    await proto.negotiate(None, None)
    await waiter
    assert waiter.done() 
開發者ID:nibrag,項目名稱:aiosocks,代碼行數:11,代碼來源:test_protocols.py

示例14: __init__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def __init__(self, node_name: str):
        """ Create connection handler object. """
        super().__init__()

        self.node_name_ = node_name
        """ Name of the running Erlang node. """

        self.packet_len_size_ = 2
        """ Packet size header is variable, 2 bytes before handshake is finished
            and 4 bytes afterwards. """

        self.addr_ = None  # type: [None, Tuple[str, int]]

        self.inbox_ = asyncio.Queue()
        """ Inbox is used to ask the connection to do something. """

        self.peer_distr_version_ = (None, None)  # type: (int, int)
        """ Protocol version range supported by the remote peer. Erlang/OTP 
            versions 19-20 supports protocol version 7, older Erlangs down to 
            R6B support version 5. """

        self.peer_flags_ = 0
        self.peer_name_ = None  # type: Union[None, str]
        self.my_challenge_ = None

        self.state_ = self.DISCONNECTED
        """ FSM state for the protocol state-machine. """

        self.transport_ = None  # type: [None, asyncio.Transport]
        self.unconsumed_data_ = b''

        self._last_interaction = time.time() 
開發者ID:Pyrlang,項目名稱:Pyrlang,代碼行數:34,代碼來源:base_dist_protocol.py

示例15: __init__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Protocol [as 別名]
def __init__(
        self,
        protocol: asyncio.Protocol,
    ) -> None:
        super().__init__()
        self._loop = asyncio.get_event_loop()
        self._protocol = protocol 
開發者ID:vmagamedov,項目名稱:grpclib,代碼行數:9,代碼來源:testing.py


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