本文整理汇总了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)
示例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
示例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
示例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)
示例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)
示例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())
示例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
示例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")
示例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)
示例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()
示例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)
示例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
示例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()
示例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()
示例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