A browser-style WebSocket over a websockets connection. Methods
may be called from any thread; listeners run on the socket loop.
pause stops reading messages until resume; buffered_amount
counts what was sent but has not reached the transport.
Attributes#
| Attribute | Type | Description |
|---|---|---|
url | str | None = None | |
ready_state | int | |
is_paused | bool | |
buffered_amount | int | |
connection | WsConnection | None | The |
Functions#
__init__#
__init__(*, paused=False, max_message_size=DEFAULT_MAX_MESSAGE_SIZE) -> None| Parameter | Type | Description |
|---|---|---|
paused | bool = False | |
max_message_size | int | None = DEFAULT_MAX_MESSAGE_SIZE |
def __init__(
self, *, paused: bool = False, max_message_size: int | None = DEFAULT_MAX_MESSAGE_SIZE
) -> None:
self._max_message_size = max_message_size
self._lock = threading.Lock()
self._listeners: dict[WebSocketEventType, list[tuple[Listener, bool]]] = {}
self._state = CONNECTING
self._paused = paused
self._outgoing: asyncio.Queue[tuple[bytes | str, int] | _Close] = asyncio.Queue()
self._unsent = _Outgoing()
self._flowing = asyncio.Event()
if not paused:
self._flowing.set()
self._abandoned = asyncio.Event()
self._task: asyncio.Task[None] | None = None
self._connection: WsConnection | None = None
self.url: str | None = Noneconnect#
connect(url, options, *, max_message_size=DEFAULT_MAX_MESSAGE_SIZE) -> WsWebSocketOpen a client connection to url; a message longer than
max_message_size bytes (None: no limit) closes it with
1009.
| Parameter | Type | Description |
|---|---|---|
url | str | |
options | WebSocketClientOptions | |
max_message_size | int | None = DEFAULT_MAX_MESSAGE_SIZE |
Returns WsWebSocket
@classmethod
def connect(
cls,
url: str,
options: WebSocketClientOptions,
*,
max_message_size: int | None = DEFAULT_MAX_MESSAGE_SIZE,
) -> WsWebSocket:
"""Open a client connection to ``url``; a message longer than
``max_message_size`` bytes (``None``: no limit) closes it with
1009."""
ws = cls(max_message_size=max_message_size)
ws.url = url
call_soon(lambda: ws._begin(url, options))
return wswhen_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:
state = self._state
if state == CONNECTING:
raise RuntimeError("WebSocket is not open: readyState 0 (CONNECTING)")
if state == OPEN:
# A browser sends a USVString: lone surrogates become U+FFFD.
message = to_well_formed(data) if isinstance(data, str) else data
size = self._unsent.queued(message)
get_loop().call_soon_threadsafe(self._outgoing.put_nowait, (message, size))close#
close(code=None, reason=None) -> NoneStart the closing handshake; as in a browser, code must be
1000 or 3000 to 4999 and reason at most 123 UTF-8 bytes.
| Parameter | Type | Description |
|---|---|---|
code | int | None = None | |
reason | str | None = None |
def close(self, code: int | None = None, reason: str | None = None) -> None:
"""Start the closing handshake; as in a browser, ``code`` must be
1000 or 3000 to 4999 and ``reason`` at most 123 UTF-8 bytes."""
if code is not None and code != 1000 and not 3000 <= code <= 4999:
raise ValueError(f"invalid WebSocket close code: {code}")
text = to_well_formed(reason or "")
if len(text_encode(text)) > 123:
raise ValueError("WebSocket close reason is longer than 123 bytes")
call_soon(lambda: self._close(1000 if code is None else code, text))pause#
pause() -> Nonedef pause(self) -> None:
self._paused = True
call_soon(self._flowing.clear)resume#
resume() -> Nonedef resume(self) -> None:
self._paused = False
call_soon(self._flowing.set)terminate#
terminate() -> NoneDrop the connection without a closing handshake.
def terminate(self) -> None:
"""Drop the connection without a closing handshake."""
def abort() -> None:
self._abandoned.set()
connection = self._connection
if connection is not None:
connection.transport.abort()
elif self._task is not None:
self._task.cancel()
call_soon(abort)