Python Glossary Русский

Python 3.11+Async programmingterm

asyncio.Server

streams

The running-server object returned by asyncio.start_server() and loop.create_server(): it accepts connections and shuts down with close() and wait_closed().

Syntax

server = await asyncio.start_server(handler, host, port)
async with server: await server.serve_forever()

The server starts accepting connections right after start_server(); serve_forever() only keeps the coroutine alive until the server is closed — without an await the program simply reaches the end of asyncio.run() and the server dies. Port 0 asks the OS for a free port, readable via server.sockets[0].getsockname(). The name asyncio.Server exists since 3.11 (and 3.9.11/3.10.3); never instantiate it.

Examples

import asyncio
async def handle(reader, writer):
    data = await reader.readline()
    writer.write(data.upper())
    await writer.drain()
    writer.close()
async def main():
    server = await asyncio.start_server(handle, '127.0.0.1', 0)  # только локальный адрес
    host, port = server.sockets[0].getsockname()[:2]
    async with server:
        reader, writer = await asyncio.open_connection(host, port)
        writer.write(b'ping\n')
        print(await reader.readline())  # → b'PING\n'
        writer.close()
        await writer.wait_closed()
    print(type(server).__name__, server.is_serving())  # → Server False
    await asyncio.sleep(0.01)
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy