Skip to content

Reference

AsyncWebSocketSession

Async context manager representing an opened WebSocket session.

Attributes:

Name Type Description
subprotocol Optional[str]

Optional protocol that has been accepted by the server.

response Optional[Response]

The webSocket handshake response.

close(code=1000, reason=None) async

Close the WebSocket session.

Internally, it'll send the CloseConnection event.

This method is automatically called when exiting the context manager.

Parameters:

Name Type Description Default
code int

The integer close code to indicate why the connection has closed.

1000
reason Optional[str]

Additional reasoning for why the connection has closed.

None

Examples:

Close the WebSocket session.

await ws.close()

ping(payload=b'') async

Send a Ping message.

Parameters:

Name Type Description Default
payload bytes

Payload to attach to the Ping event. Internally, it's used to track this specific event. If left empty, a random one will be generated.

b''

Returns:

Type Description
Event

An event that can be used to wait for the corresponding Pong response.

Examples:

Send a Ping and wait for the Pong

pong_callback = await ws.ping()
# Will block until the corresponding Pong is received.
await pong_callback.wait()

receive(timeout=None) async

Receive an event from the server.

Mainly useful to receive raw wsproto.events.Event. Most of the time, receive_text(), receive_bytes(), and receive_json() are preferred.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
Event

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

Examples:

Wait for an event until one is available.

try:
    event = await ws.receive()
except WebSocketDisconnect:
    print("Connection closed")

Wait for an event for 2 seconds.

try:
    event = await ws.receive(timeout=2.)
except TimeoutError:
    print("No event received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_bytes(timeout=None) async

Receive bytes from the server.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
bytes

Bytes data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a bytes message.

Examples:

Wait for bytes until available.

try:
    data = await ws.receive_bytes()
except WebSocketDisconnect:
    print("Connection closed")

Wait for bytes for 2 seconds.

try:
    data = await ws.receive_bytes(timeout=2.)
except TimeoutError:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_json(timeout=None, mode='text') async

Receive JSON data from the server.

The received data should be parseable by json.loads.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None
mode JSONMode

Receive mode. Should either be 'text' or 'bytes'.

'text'

Returns:

Type Description
Any

Parsed JSON data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event didn't correspond to the specified mode.

Examples:

Wait for data until available.

try:
    data = await ws.receive_json()
except WebSocketDisconnect:
    print("Connection closed")

Wait for data for 2 seconds.

try:
    data = await ws.receive_json(timeout=2.)
except TimeoutError:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_text(timeout=None) async

Receive text from the server.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
str

Text data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a text message.

Examples:

Wait for text until available.

try:
    text = await ws.receive_text()
except WebSocketDisconnect:
    print("Connection closed")

Wait for text for 2 seconds.

try:
    event = await ws.receive_text(timeout=2.)
except TimeoutError:
    print("No text received.")
except WebSocketDisconnect:
    print("Connection closed")

send(event) async

Send an Event message.

Mainly useful to send events that are not supported by the library. Most of the time, ping(), send_text(), send_bytes() and send_json() are preferred.

Parameters:

Name Type Description Default
event Event

The event to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send an event.

event = await wsproto.events.Message(b"Hello!")
ws.send(event)

send_bytes(data) async

Send a bytes message.

Parameters:

Name Type Description Default
data bytes

The data to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send a bytes message.

await ws.send_bytes(b"Hello!")

send_json(data, mode='text') async

Send JSON data.

Parameters:

Name Type Description Default
data Any

The data to send. Must be serializable by json.dumps.

required
mode JSONMode

The sending mode. Should either be 'text' or 'bytes'.

'text'

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send JSON data.

data = {"message": "Hello!"}
await ws.send_json(data)

send_text(data) async

Send a text message.

Parameters:

Name Type Description Default
data str

The text to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send a text message.

await ws.send_text("Hello!")

HTTPXWSException

Bases: Exception

Base exception class for HTTPX WS.

WebSocketDisconnect

Bases: HTTPXWSException

Raised when the server closed the WebSocket session.

Parameters:

Name Type Description Default
code int

The integer close code to indicate why the connection has closed.

1000
reason Optional[str]

Additional reasoning for why the connection has closed.

None

WebSocketInvalidTypeReceived

Bases: HTTPXWSException

Raised when a event is not of the expected type.

WebSocketNetworkError

Bases: HTTPXWSException

Raised when a network error occured, typically if the underlying stream has closed or timeout.

WebSocketSession

Sync context manager representing an opened WebSocket session.

Attributes:

Name Type Description
subprotocol Optional[str]

Optional protocol that has been accepted by the server.

response Optional[Response]

The webSocket handshake response.

close(code=1000, reason=None)

Close the WebSocket session.

Internally, it'll send the CloseConnection event.

This method is automatically called when exiting the context manager.

Parameters:

Name Type Description Default
code int

The integer close code to indicate why the connection has closed.

1000
reason Optional[str]

Additional reasoning for why the connection has closed.

None

Examples:

Close the WebSocket session.

ws.close()

ping(payload=b'')

Send a Ping message.

Parameters:

Name Type Description Default
payload bytes

Payload to attach to the Ping event. Internally, it's used to track this specific event. If left empty, a random one will be generated.

b''

Returns:

Type Description
Event

An event that can be used to wait for the corresponding Pong response.

Examples:

Send a Ping and wait for the Pong

pong_callback = ws.ping()
# Will block until the corresponding Pong is received.
pong_callback.wait()

receive(timeout=None)

Receive an event from the server.

Mainly useful to receive raw wsproto.events.Event. Most of the time, receive_text(), receive_bytes(), and receive_json() are preferred.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
Event

Raises:

Type Description
Empty

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

Examples:

Wait for an event until one is available.

try:
    event = ws.receive()
except WebSocketDisconnect:
    print("Connection closed")

Wait for an event for 2 seconds.

try:
    event = ws.receive(timeout=2.)
except queue.Empty:
    print("No event received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_bytes(timeout=None)

Receive bytes from the server.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
bytes

Bytes data.

Raises:

Type Description
Empty

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a bytes message.

Examples:

Wait for bytes until available.

try:
    data = ws.receive_bytes()
except WebSocketDisconnect:
    print("Connection closed")

Wait for bytes for 2 seconds.

try:
    data = ws.receive_bytes(timeout=2.)
except queue.Empty:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_json(timeout=None, mode='text')

Receive JSON data from the server.

The received data should be parseable by json.loads.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None
mode JSONMode

Receive mode. Should either be 'text' or 'bytes'.

'text'

Returns:

Type Description
Any

Parsed JSON data.

Raises:

Type Description
Empty

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event didn't correspond to the specified mode.

Examples:

Wait for data until available.

try:
    data = ws.receive_json()
except WebSocketDisconnect:
    print("Connection closed")

Wait for data for 2 seconds.

try:
    data = ws.receive_json(timeout=2.)
except queue.Empty:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_text(timeout=None)

Receive text from the server.

Parameters:

Name Type Description Default
timeout Optional[float]

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
str

Text data.

Raises:

Type Description
Empty

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a text message.

Examples:

Wait for text until available.

try:
    text = ws.receive_text()
except WebSocketDisconnect:
    print("Connection closed")

Wait for text for 2 seconds.

try:
    event = ws.receive_text(timeout=2.)
except queue.Empty:
    print("No text received.")
except WebSocketDisconnect:
    print("Connection closed")

send(event)

Send an Event message.

Mainly useful to send events that are not supported by the library. Most of the time, ping(), send_text(), send_bytes() and send_json() are preferred.

Parameters:

Name Type Description Default
event Event

The event to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send an event.

event = wsproto.events.Message(b"Hello!")
ws.send(event)

send_bytes(data)

Send a bytes message.

Parameters:

Name Type Description Default
data bytes

The data to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send a bytes message.

ws.send_bytes(b"Hello!")

send_json(data, mode='text')

Send JSON data.

Parameters:

Name Type Description Default
data Any

The data to send. Must be serializable by json.dumps.

required
mode JSONMode

The sending mode. Should either be 'text' or 'bytes'.

'text'

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send JSON data.

data = {"message": "Hello!"}
ws.send_json(data)

send_text(data)

Send a text message.

Parameters:

Name Type Description Default
data str

The text to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send a text message.

ws.send_text("Hello!")

WebSocketUpgradeError

Bases: HTTPXWSException

Raised when the initial connection didn't correctly upgrade to a WebSocket session.

aconnect_ws(url, client=None, *, max_message_size_bytes=DEFAULT_MAX_MESSAGE_SIZE_BYTES, queue_size=DEFAULT_QUEUE_SIZE, keepalive_ping_interval_seconds=DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS, keepalive_ping_timeout_seconds=DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS, subprotocols=None, **kwargs) async

Start an async WebSocket session.

It returns an async context manager that'll automatically call close() when exiting.

Parameters:

Name Type Description Default
url str

The WebSocket URL.

required
client Optional[AsyncClient]

HTTPX client to use. If not provided, a default one will be initialized.

None
max_message_size_bytes int

Message size in bytes to receive from the server. Defaults to 65 KiB.

DEFAULT_MAX_MESSAGE_SIZE_BYTES
queue_size int

Size of the queue where the received messages will be held until they are consumed. If the queue is full, the client will stop receive messages from the server until the queue has room available. Defaults to 512.

DEFAULT_QUEUE_SIZE
keepalive_ping_interval_seconds Optional[float]

Interval at which the client will automatically send a Ping event to keep the connection alive. Set it to None to disable this mechanism. Defaults to 20 seconds.

DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS
keepalive_ping_timeout_seconds Optional[float]

Maximum delay the client will wait for an answer to its Ping event. If the delay is exceeded, WebSocketNetworkError will be raised and the connection closed. Defaults to 20 seconds.

DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS
subprotocols Optional[list[str]]

Optional list of suprotocols to negotiate with the server.

None
**kwargs Any

Additional keyword arguments that will be passed to the HTTPX stream() method.

{}

Returns:

Type Description
AsyncGenerator[AsyncWebSocketSession, None]

Examples:

Without explicit HTTPX client.

async with aconnect_ws("http://localhost:8000/ws") as ws:
    message = await ws.receive_text()
    print(message)
    await ws.send_text("Hello!")

With explicit HTTPX client.

async with httpx.AsyncClient() as client:
    async with aconnect_ws("http://localhost:8000/ws", client) as ws:
        message = await ws.receive_text()
        print(message)
        await ws.send_text("Hello!")

connect_ws(url, client=None, *, max_message_size_bytes=DEFAULT_MAX_MESSAGE_SIZE_BYTES, queue_size=DEFAULT_QUEUE_SIZE, keepalive_ping_interval_seconds=DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS, keepalive_ping_timeout_seconds=DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS, subprotocols=None, **kwargs)

Start a sync WebSocket session.

It returns a context manager that'll automatically call close() when exiting.

Parameters:

Name Type Description Default
url str

The WebSocket URL.

required
client Optional[Client]

HTTPX client to use. If not provided, a default one will be initialized.

None
max_message_size_bytes int

Message size in bytes to receive from the server. Defaults to 65 KiB.

DEFAULT_MAX_MESSAGE_SIZE_BYTES
queue_size int

Size of the queue where the received messages will be held until they are consumed. If the queue is full, the client will stop receive messages from the server until the queue has room available. Defaults to 512.

DEFAULT_QUEUE_SIZE
keepalive_ping_interval_seconds Optional[float]

Interval at which the client will automatically send a Ping event to keep the connection alive. Set it to None to disable this mechanism. Defaults to 20 seconds.

DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS
keepalive_ping_timeout_seconds Optional[float]

Maximum delay the client will wait for an answer to its Ping event. If the delay is exceeded, WebSocketNetworkError will be raised and the connection closed. Defaults to 20 seconds.

DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS
subprotocols Optional[list[str]]

Optional list of suprotocols to negotiate with the server.

None
**kwargs Any

Additional keyword arguments that will be passed to the HTTPX stream() method.

{}

Returns:

Type Description
None

Examples:

Without explicit HTTPX client.

with connect_ws("http://localhost:8000/ws") as ws:
    message = ws.receive_text()
    print(message)
    ws.send_text("Hello!")

With explicit HTTPX client.

with httpx.Client() as client:
    with connect_ws("http://localhost:8000/ws", client) as ws:
        message = ws.receive_text()
        print(message)
        ws.send_text("Hello!")