Skip to content

serve_ws

autogen.beta.network.transport.ws.serve_ws async #

serve_ws(hub, host, port, *, ssl_context=None, ping_interval=20.0, ping_timeout=20.0)

Run a WebSocket server bound to a hub.

Each incoming connection becomes a :class:WsLinkEndpoint attached via :meth:Hub.attach_endpoint; the hub's existing frame-processor handles routing. Yields the underlying websockets Server so callers can inspect the bound address (server.sockets[0].getsockname() is the usual way to read the actual port when port=0 was passed).

The context manager closes the server on exit and waits for all handler tasks to finish so the hub's endpoint registry is clean.

Source code in autogen/beta/network/transport/ws.py
@contextlib.asynccontextmanager
async def serve_ws(
    hub: "Hub",
    host: str,
    port: int,
    *,
    ssl_context: Any = None,
    ping_interval: float | None = 20.0,
    ping_timeout: float | None = 20.0,
) -> AsyncIterator["_WsServer"]:
    """Run a WebSocket server bound to a hub.

    Each incoming connection becomes a :class:`WsLinkEndpoint`
    attached via :meth:`Hub.attach_endpoint`; the hub's existing
    frame-processor handles routing. Yields the underlying
    ``websockets`` ``Server`` so callers can inspect the bound
    address (``server.sockets[0].getsockname()`` is the usual way to
    read the actual port when ``port=0`` was passed).

    The context manager closes the server on exit and waits for all
    handler tasks to finish so the hub's endpoint registry is clean.
    """
    server = await _ws_serve(
        functools.partial(_serve_connection, hub),
        host,
        port,
        ssl=ssl_context,
        ping_interval=ping_interval,
        ping_timeout=ping_timeout,
    )
    try:
        yield server
    finally:
        server.close()
        with contextlib.suppress(asyncio.CancelledError, Exception):
            await server.wait_closed()