Python Glossary Русский

Python 3.4+Async programmingfunction

asyncio.open_connection()

streams

Opens a TCP connection and returns a (StreamReader, StreamWriter) pair for reading and writing bytes with await.

Syntax

reader, writer = await asyncio.open_connection(host=None, port=None, *, limit=2**16, ssl=None, sock=None, **kwds)

writer.write() is not a coroutine: bytes go to a buffer, and only await writer.drain() waits for it to empty; skip it and a fast sender bloats memory. reader.readline() on a closed connection returns b'' instead of raising, so a read loop must check for the empty result. Close with writer.close() followed by await writer.wait_closed(). It also accepts a ready socket via sock=.

Examples

import asyncio
async def echo(reader, writer):
    writer.write(await reader.readline())
    await writer.drain()
    writer.close()
async def main():
    server = await asyncio.start_server(echo, '127.0.0.1', 0)
    port = server.sockets[0].getsockname()[1]
    async with server:
        reader, writer = await asyncio.open_connection('127.0.0.1', port)
        writer.write(b'hello\n')
        await writer.drain()
        print(await reader.readline())  # → b'hello\n'
        print(await reader.readline())  # → b'' — соединение закрыто, не исключение
        writer.close()
        await writer.wait_closed()
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy