本文整理匯總了Python中asyncio.StreamReader方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.StreamReader方法的具體用法?Python asyncio.StreamReader怎麽用?Python asyncio.StreamReader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類asyncio
的用法示例。
在下文中一共展示了asyncio.StreamReader方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: handshake
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def handshake(
remote: kademlia.Node, privkey: datatypes.PrivateKey, token: CancelToken
) -> Tuple[
bytes, bytes, BasePreImage, BasePreImage, asyncio.StreamReader, asyncio.StreamWriter
]: # noqa: E501
"""
Perform the auth handshake with given remote.
Returns the established secrets and the StreamReader/StreamWriter pair already connected to
the remote.
"""
use_eip8 = False
initiator = HandshakeInitiator(remote, privkey, use_eip8, token)
reader, writer = await initiator.connect()
opened_connections[remote.__repr__()] = (reader, writer)
aes_secret, mac_secret, egress_mac, ingress_mac = await _handshake(
initiator, reader, writer, token
)
return aes_secret, mac_secret, egress_mac, ingress_mac, reader, writer
示例2: __init__
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def __init__(
self,
app: ASGIFramework,
loop: asyncio.AbstractEventLoop,
config: Config,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
) -> None:
self.app = app
self.config = config
self.loop = loop
self.protocol: ProtocolWrapper
self.reader = reader
self.writer = writer
self.send_lock = asyncio.Lock()
self.timeout_lock = asyncio.Lock()
self._keep_alive_timeout_handle: Optional[asyncio.Task] = None
示例3: test_it_logs_messages
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def test_it_logs_messages(self):
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
async def test():
reader = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(reader)
transport, _ = await loop.connect_read_pipe(
lambda: protocol, self.read_pipe
)
logger = Logger.with_default_handlers()
await logger.info("Xablau")
logged_content = await reader.readline()
self.assertEqual(logged_content, b"Xablau\n")
transport.close()
await logger.shutdown()
loop.run_until_complete(test())
示例4: create_pipe_streams_pair
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def create_pipe_streams_pair():
path = tempfile.mktemp()
loop = asyncio.get_event_loop()
server_side = asyncio.Future()
def factory():
def client_connected_cb(reader, writer):
server_side.set_result((reader, writer))
reader = asyncio.StreamReader(loop=loop)
return asyncio.StreamReaderProtocol(reader, client_connected_cb, loop=loop)
server = yield from loop.create_unix_server(factory, path)
r1 = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(r1, loop=loop)
transport, _ = yield from loop.create_unix_connection(
lambda: protocol, path)
w1 = asyncio.StreamWriter(transport, protocol, r1, loop)
r2, w2 = yield from server_side
server.close()
return (r1, w1), (r2, w2)
示例5: test_readline
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def test_readline(self):
# Read one line. 'readline' will need to wait for the data
# to come from 'cb'
stream = asyncio.StreamReader(loop=self.loop)
stream.feed_data(b'chunk1 ')
read_task = asyncio.Task(stream.readline(), loop=self.loop)
def cb():
stream.feed_data(b'chunk2 ')
stream.feed_data(b'chunk3 ')
stream.feed_data(b'\n chunk4')
self.loop.call_soon(cb)
line = self.loop.run_until_complete(read_task)
self.assertEqual(b'chunk1 chunk2 chunk3 \n', line)
self.assertEqual(b' chunk4', stream._buffer)
示例6: test_readexactly
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def test_readexactly(self):
# Read exact number of bytes.
stream = asyncio.StreamReader(loop=self.loop)
n = 2 * len(self.DATA)
read_task = asyncio.Task(stream.readexactly(n), loop=self.loop)
def cb():
stream.feed_data(self.DATA)
stream.feed_data(self.DATA)
stream.feed_data(self.DATA)
self.loop.call_soon(cb)
data = self.loop.run_until_complete(read_task)
self.assertEqual(self.DATA + self.DATA, data)
self.assertEqual(self.DATA, stream._buffer)
示例7: test_readexactly_eof
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def test_readexactly_eof(self):
# Read exact number of bytes (eof).
stream = asyncio.StreamReader(loop=self.loop)
n = 2 * len(self.DATA)
read_task = asyncio.Task(stream.readexactly(n), loop=self.loop)
def cb():
stream.feed_data(self.DATA)
stream.feed_eof()
self.loop.call_soon(cb)
with self.assertRaises(asyncio.IncompleteReadError) as cm:
self.loop.run_until_complete(read_task)
self.assertEqual(cm.exception.partial, self.DATA)
self.assertEqual(cm.exception.expected, n)
self.assertEqual(str(cm.exception),
'18 bytes read on a total of 36 expected bytes')
self.assertEqual(b'', stream._buffer)
示例8: _wait_for_data
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def _wait_for_data(self, func_name):
"""Wait until feed_data() or feed_eof() is called.
If stream was paused, automatically resume it.
"""
# StreamReader uses a future to link the protocol feed_data() method
# to a read coroutine. Running two read coroutines at the same time
# would have an unexpected behaviour. It would not possible to know
# which coroutine would get the next data.
if self._waiter is not None:
raise RuntimeError('%s() called while another coroutine is '
'already waiting for incoming data' % func_name)
assert not self._eof, '_wait_for_data after EOF'
# Waiting for data while paused will make deadlock, so prevent it.
if self._paused:
self._paused = False
self._transport.resume_reading()
self._waiter = asyncio.futures.Future(loop=self._loop)
try:
await self._waiter
finally:
self._waiter = None
示例9: __call__
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def __call__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
"""Main entry point for an interpreter session with a single client."""
self.reader = reader
self.writer = writer
self.running = True
if self.banner:
writer.write(self.banner)
await writer.drain()
while self.running:
try:
await self.handle_one_command()
except ConnectionResetError:
writer.close()
self.running = False
break
except Exception:
log.exception("Exception in manhole REPL")
self.writer.write(traceback.format_exc())
await self.writer.drain()
示例10: open_serial_connection
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def open_serial_connection(*,
loop=None,
limit=asyncio.streams._DEFAULT_LIMIT,
**kwargs):
"""A wrapper for create_serial_connection() returning a (reader,
writer) pair.
The reader returned is a StreamReader instance; the writer is a
StreamWriter instance.
The arguments are all the usual arguments to Serial(). Additional
optional keyword arguments are loop (to set the event loop instance
to use) and limit (to set the buffer limit passed to the
StreamReader.
This function is a coroutine.
"""
if loop is None:
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader(limit=limit, loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
transport, _ = yield from create_serial_connection(
loop=loop,
protocol_factory=lambda: protocol,
**kwargs)
writer = asyncio.StreamWriter(transport, protocol, reader, loop)
return reader, writer
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# test
示例11: open_connection
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def open_connection(host=None, port=None, *,
limit, loop=None,
parser=None, **kwds):
# XXX: parser is not used (yet)
if loop is not None and sys.version_info >= (3, 8):
warnings.warn("The loop argument is deprecated",
DeprecationWarning)
reader = StreamReader(limit=limit)
protocol = asyncio.StreamReaderProtocol(reader)
transport, _ = await get_event_loop().create_connection(
lambda: protocol, host, port, **kwds)
writer = asyncio.StreamWriter(transport, protocol, reader,
loop=get_event_loop())
return reader, writer
示例12: open_unix_connection
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def open_unix_connection(address, *,
limit, loop=None,
parser=None, **kwds):
# XXX: parser is not used (yet)
if loop is not None and sys.version_info >= (3, 8):
warnings.warn("The loop argument is deprecated",
DeprecationWarning)
reader = StreamReader(limit=limit)
protocol = asyncio.StreamReaderProtocol(reader)
transport, _ = await get_event_loop().create_unix_connection(
lambda: protocol, address, **kwds)
writer = asyncio.StreamWriter(transport, protocol, reader,
loop=get_event_loop())
return reader, writer
示例13: _handshake
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def _handshake(
initiator: "HandshakeInitiator",
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
token: CancelToken,
) -> Tuple[bytes, bytes, BasePreImage, BasePreImage]:
"""See the handshake() function above.
This code was factored out into this helper so that we can create Peers with directly
connected readers/writers for our tests.
"""
initiator_nonce = keccak(os.urandom(HASH_LEN))
auth_msg = initiator.create_auth_message(initiator_nonce)
auth_init = initiator.encrypt_auth_message(auth_msg)
writer.write(auth_init)
auth_ack = await token.cancellable_wait(
reader.read(ENCRYPTED_AUTH_ACK_LEN), timeout=REPLY_TIMEOUT
)
if reader.at_eof():
# This is what happens when Parity nodes have blacklisted us
# (https://github.com/ethereum/py-evm/issues/901).
raise HandshakeDisconnectedFailure(
"%s disconnected before sending auth ack", repr(initiator.remote)
)
ephemeral_pubkey, responder_nonce = initiator.decode_auth_ack_message(auth_ack)
aes_secret, mac_secret, egress_mac, ingress_mac = initiator.derive_secrets(
initiator_nonce, responder_nonce, ephemeral_pubkey, auth_init, auth_ack
)
return aes_secret, mac_secret, egress_mac, ingress_mac
示例14: connect
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def connect(self) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
return await self.cancel_token.cancellable_wait(
asyncio.open_connection(
host=self.remote.address.ip, port=self.remote.address.tcp_port
),
timeout=REPLY_TIMEOUT,
)
示例15: receive_handshake
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamReader [as 別名]
def receive_handshake(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
ip, socket, *_ = writer.get_extra_info("peername")
remote_address = Address(ip, socket)
if self.peer_pool.chk_dialin_blacklist(remote_address):
Logger.info_every_n(
"{} has been blacklisted, refusing connection".format(remote_address),
100,
)
reader.feed_eof()
writer.close()
expected_exceptions = (
TimeoutError,
PeerConnectionLost,
HandshakeFailure,
asyncio.IncompleteReadError,
HandshakeDisconnectedFailure,
)
try:
await self._receive_handshake(reader, writer)
except expected_exceptions as e:
self.logger.debug("Could not complete handshake: %s", e)
Logger.error_every_n("Could not complete handshake: {}".format(e), 100)
reader.feed_eof()
writer.close()
except OperationCancelled:
self.logger.error("OperationCancelled")
reader.feed_eof()
writer.close()
except Exception as e:
self.logger.exception("Unexpected error handling handshake")
reader.feed_eof()
writer.close()