A browser-style WebSocket over an ASGI websocket connection.
Methods may be called from any thread; listeners run on the server's
loop. Messages wait (one at a time) while paused; buffered_amount
counts what was sent but the server has not taken.
Attributes#
| Attribute | Type | Description |
|---|---|---|
lost | asyncio.Event = asyncio.Event() | Set when the connection ends without a closing handshake. |
ready_state | int | |
is_paused | bool | |
buffered_amount | int | |
accepted | bool |
Functions#
__init__#
__init__(receive, send) -> None| Parameter | Type | Description |
|---|---|---|
receive | Receive | |
send | Send |
def __init__(self, receive: Receive, send: Send) -> None:
self._loop = asyncio.get_running_loop()
self._receive = receive
self._send = send
self._lock = threading.Lock()
self._listeners: dict[WebSocketEventType, list[tuple[Listener, bool]]] = {}
self._state = CONNECTING
self._paused = True
self._flowing = asyncio.Event()
self._outgoing: asyncio.Queue[tuple[Message, int] | None] = asyncio.Queue()
self._unsent = Outgoing()
self._writer: asyncio.Task[None] | None = None
self._closing = False
self.lost: asyncio.Event = asyncio.Event()
"""Set when the connection ends without a closing handshake."""
self._reader = self._loop.create_task(self._read())when_drained#
when_drained(below, callback) -> Callable[[], None]| Parameter | Type | Description |
|---|---|---|
below | int | |
callback | Callable[[], None] |
Returns Callable[[], None]
def when_drained(self, below: int, callback: Callable[[], None]) -> Callable[[], None]:
return self._unsent.when_drained(below, callback)add_event_listener#
add_event_listener(type, listener, *, once=False) -> None| Parameter | Type | Description |
|---|---|---|
type | WebSocketEventType | |
listener | Listener | |
once | bool = False |
def add_event_listener(
self, type: WebSocketEventType, listener: Listener, *, once: bool = False
) -> None:
with self._lock:
entries = self._listeners.setdefault(type, [])
if all(entry is not listener for entry, _ in entries):
entries.append((listener, once))remove_event_listener#
remove_event_listener(type, listener) -> None| Parameter | Type | Description |
|---|---|---|
type | WebSocketEventType | |
listener | Listener |
def remove_event_listener(self, type: WebSocketEventType, listener: Listener) -> None:
with self._lock:
entries = self._listeners.get(type, [])
entries[:] = [(entry, once) for entry, once in entries if entry is not listener]send#
send(data) -> None| Parameter | Type | Description |
|---|---|---|
data | bytes | str |
def send(self, data: bytes | str) -> None:
if self._state == CONNECTING:
raise RuntimeError("WebSocket is not open: readyState 0 (CONNECTING)")
if self._state == OPEN:
message: Message = (
{"type": "websocket.send", "text": data}
if isinstance(data, str)
else {"type": "websocket.send", "bytes": data}
)
size = self._unsent.queued(data)
self._loop.call_soon_threadsafe(self._outgoing.put_nowait, (message, size))close#
close(code=None, reason=None) -> None| Parameter | Type | Description |
|---|---|---|
code | int | None = None | |
reason | str | None = None |
def close(self, code: int | None = None, reason: str | None = None) -> None:
self._loop.call_soon_threadsafe(self._close, 1000 if code is None else code, reason or "")pause#
pause() -> Nonedef pause(self) -> None:
self._paused = True
self._loop.call_soon_threadsafe(self._flowing.clear)resume#
resume() -> Nonedef resume(self) -> None:
self._paused = False
self._loop.call_soon_threadsafe(self._flowing.set)accept#
accept(subprotocol) -> None| Parameter | Type | Description |
|---|---|---|
subprotocol | str | None |
async def accept(self, subprotocol: str | None) -> None:
if self._state != CONNECTING:
raise ConnectionError("The socket closed before the upgrade")
await self._send({"type": "websocket.accept", "subprotocol": subprotocol})
if not self._move(OPEN):
raise ConnectionError("The socket closed during the upgrade")
self._writer = self._loop.create_task(self._write())
self._dispatch("open", WebSocketEvent(type="open"))finish#
finish() -> NoneOnce the handler is done: close the connection if it is still open, send what is queued, and stop reading.
async def finish(self) -> None:
"""Once the handler is done: close the connection if it is still
open, send what is queued, and stop reading."""
self._close(1000, "")
if self._writer is not None:
await self._writer
self._reader.cancel()