GitHub

AsgiWebSocket

API reference for AsgiWebSocket.

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

AttributeTypeDescription
lostasyncio.Event = asyncio.Event()

Set when the connection ends without a closing handshake.

ready_stateint
is_pausedbool
buffered_amountint
acceptedbool

Functions

__init__

__init__(receive, send) -> None
ParameterTypeDescription
receiveReceive
sendSend
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]
ParameterTypeDescription
belowint
callbackCallable[[], 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
ParameterTypeDescription
typeWebSocketEventType
listenerListener
oncebool = 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
ParameterTypeDescription
typeWebSocketEventType
listenerListener
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
ParameterTypeDescription
databytes | 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
ParameterTypeDescription
codeint | None = None
reasonstr | 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() -> None
def pause(self) -> None:
    self._paused = True
    self._loop.call_soon_threadsafe(self._flowing.clear)

resume

resume() -> None
def resume(self) -> None:
    self._paused = False
    self._loop.call_soon_threadsafe(self._flowing.set)

accept

accept(subprotocol) -> None
ParameterTypeDescription
subprotocolstr | 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() -> None

Once 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()