WebSocket Client

The WebSocket client module provides functionality

WebSocket Client Module

This module implements a WebSocket client for aiosonic. It provides a WebSocketConnection class for managing WebSocket connections (including sending/receiving text, binary, and JSON messages, ping/pong keep-alive, and graceful closing) and a WebSocketClient class for performing the HTTP upgrade handshake and connecting to a WebSocket server.

Classes:
Message

Represents a WebSocket message.

ProtocolHandler

Base class for custom protocol encoding/decoding.

WebSocketConnection

Manages a WebSocket connection, including an async iterator to receive normal messages.

WebSocketClient

Establishes a WebSocket connection.

Exceptions:
ConnectionDisconnected

Raised when the connection is unexpectedly closed.

ReadTimeout

Raised when a read operation times out.

class aiosonic.web_socket_client.Message(type: aiosonic.web_socket_client.MessageType, data: str | bytes, raw_data: bytes, opcode: int)

Bases: object

classmethod create_binary(data: bytes) Message
classmethod create_text(data: str) Message
data: str | bytes
opcode: int
raw_data: bytes
type: MessageType
class aiosonic.web_socket_client.MessageType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

BINARY = 'binary'
CLOSE = 'close'
PING = 'ping'
PONG = 'pong'
TEXT = 'text'
class aiosonic.web_socket_client.ProtocolHandler

Bases: ABC

Base class for WebSocket subprotocol handlers.

To implement a custom protocol (e.g. MessagePack), subclass this base class and implement the encode and decode methods.

abstract decode(data: bytes)
abstract encode(data) bytes
abstract property name: str
class aiosonic.web_socket_client.WebSocketClient(connector: TCPConnector | None = None)

Bases: object

async connect(url: str, verify: bool = True, ssl: SSLContext | None = None, headers: Dict[str, str] | None = None, subprotocols: List[str] | None = None, start_keepalive: bool = True, keepalive_interval: float = 30.0, conn_opts: dict | None = None) WebSocketConnection
class aiosonic.web_socket_client.WebSocketConnection(conn, queue_maxsize: int = 100, drop_frames: bool = False, protocol_handler: ProtocolHandler | None = None)

Bases: object

Manages an active WebSocket connection.

This class handles the WebSocket protocol details including: - Sending/receiving text and binary messages - Frame masking and unmasking - Ping/pong for connection keep-alive - Protocol handlers for custom message formats - Connection lifecycle management

Args:

conn: The underlying network connection queue_maxsize (int): Maximum size of the message queue (default: 100) drop_frames (bool): Whether to drop frames when queue is full (default: False) protocol_handler (ProtocolHandler): Optional handler for custom protocols

Attributes:

connected (bool): Whether the connection is currently active close_code (Optional[int]): The close code if connection was closed subprotocol (Optional[str]): The negotiated subprotocol if any

Example:

async with WebSocketClient() as client:
    # Connect to a WebSocket server
    conn = await client.connect('ws://example.com/ws')

    # Start reading messages in a loop
    async for msg in conn:
        if msg.type == MessageType.TEXT:
            print(f"Received text: {msg.data}")
        elif msg.type == MessageType.BINARY:
            print(f"Received binary data of length: {len(msg.data)}")

        # Connection will auto-close after loop ends or when
        # server disconnects
OPCODE_BINARY = 2
OPCODE_CLOSE = 8
OPCODE_PING = 9
OPCODE_PONG = 10
OPCODE_TEXT = 1
async close(code: int = 1000, reason: str = '')
async ping(data: bytes = b'')
async receive_bytes(timeout: float | None = None) bytes
async receive_json(timeout: float | None = None)
async receive_pong(timeout: float | None = None) bytes
async receive_protocol(timeout: float | None = None)
async receive_text(timeout: float | None = None) str
async send_bytes(data: bytes)
async send_json(data)
async send_protocol(data)
async send_text(message: str)
start_keep_alive(interval: float = 30.0)
stop_keep_alive()