websocket_transport module
WebSocket Transport
Real network transport implemented with aiohttp.
Provides concrete implementations of
TransportConnection,
TransportServer, and
TransportClient that communicate over
WebSocket connections.
The server exposes a /ws HTTP endpoint. Each accepted WebSocket is
wrapped in a WebSocketConnection that feeds incoming messages into
an asyncio.Queue via a background reader task.
- class network.websocket_transport.WebSocketClient(host: str, port: int)
Bases:
TransportClientaiohttp-based WebSocket client implementing
TransportClient.- Parameters:
host (str) – The server hostname or IP to connect to.
port (int) – The server port.
- async close_session()
Close the underlying
aiohttp.ClientSession.
- async connect() TransportConnection
Open a WebSocket connection to the server.
- Returns:
A connection object for sending and receiving messages.
- Return type:
- class network.websocket_transport.WebSocketConnection(ws)
Bases:
TransportConnectionWraps an aiohttp WebSocket (server- or client-side).
Incoming messages are read by a background
asyncio.Taskand placed into an internalasyncio.Queueso thatrecv()never blocks the event loop.- Parameters:
ws – The underlying aiohttp WebSocket response.
- async close() None
Close the WebSocket and cancel the background reader.
- property closed: bool
Whether this connection has been closed.
- Return type:
bool
- async recv() str
Wait for and return the next text message.
- Returns:
The received text payload.
- Return type:
str
- Raises:
ConnectionError – If the connection is closed with no queued data.
- async send(data: str) None
Send a text message over the WebSocket.
- Parameters:
data (str) – The text payload to send.
- Raises:
ConnectionError – If the connection is already closed.
- start_reading(loop=None)
Start a background task that reads WS frames into the recv queue.
- Parameters:
loop – Unused; kept for API compatibility.
- class network.websocket_transport.WebSocketServer(host='0.0.0.0', port=8765)
Bases:
TransportServeraiohttp-based WebSocket server implementing
TransportServer.Listens on the given host and port, accepting WebSocket connections at the
/wsendpoint.- Parameters:
host (str) – Bind address (default
"0.0.0.0"for all interfaces).port (int) – TCP port to listen on.
- get_join_address() str
Return a
host:portstring that clients can use to connect.- Return type:
str
- on_connection(handler) None
Register a coroutine to handle each new WebSocket connection.
- Parameters:
handler – An
async def handler(conn)coroutine.
- async start() None
Create the aiohttp application and begin listening for connections.
- async stop() None
Close all active connections and shut down the HTTP server.