WebSockets
Relevant source files
The following files were used as context for generating this wiki page:
Starlette provides a comprehensive system for handling WebSocket connections through high-level abstractions over the ASGI protocol. It facilitates persistent, bidirectional communication between clients and servers, supporting various data formats such as text, bytes, and JSON.
The WebSocket implementation is built around the WebSocket class, which manages connection state, message passing, and protocol-specific extensions like denial responses. It integrates seamlessly with Starlette's routing system via WebSocketRoute and offers a class-based approach through WebSocketEndpoint.
Architecture and Core Components
The WebSocket system relies on a state-machine-driven interaction between the client and the application. This ensures that operations like sending or receiving data only occur when the connection is in a valid state.
State Management
Starlette tracks two independent states for every WebSocket connection: client_state (what the client has sent) and application_state (what the app has sent). These states are defined by the WebSocketState enum.
| State | Description |
|---|---|
CONNECTING | Initial state before the handshake is accepted or rejected. |
CONNECTED | Connection is active; bidirectional data transfer is allowed. |
DISCONNECTED | Connection has been closed by either party. |
RESPONSE | The application is sending an HTTP denial response instead of upgrading. |
Sources: starlette/websockets.py:12-18, starlette/websockets.py:32-33
The WebSocket Class
The WebSocket class inherits from HTTPConnection and provides the primary API for developers. It handles the underlying ASGI receive and send channels.
The diagram shows the inheritance from HTTPConnection, which provides access to common attributes like headers and query parameters.
Sources: starlette/websockets.py:27-33, starlette/websockets.py:128-132
Connection Lifecycle
The lifecycle of a WebSocket connection follows a strict sequence of ASGI messages: websocket.connect, followed by websocket.accept or websocket.close.
Connection Flow
The following sequence diagram illustrates the typical handshake and communication flow:
This diagram depicts the transition from the initial connect message to active communication and eventual closure.
Sources: starlette/websockets.py:35-86, tests/test_websockets.py:11-20
Sending Denial Responses
If a server supports the websocket.http.response extension, Starlette can return a standard HTTP response (like a 403 Forbidden) instead of accepting the WebSocket upgrade. This is handled via send_denial_response.
Sources: starlette/websockets.py:169-173, tests/test_websockets.py:284-290
Routing and Endpoints
WebSockets are integrated into the application using specific routing classes and endpoint abstractions.
WebSocketRoute
The WebSocketRoute class is used within a Router to map URL paths to WebSocket endpoints. It functions similarly to standard Route but specifically handles the websocket scope type.
Sources: starlette/routing.py:382-386
WebSocketEndpoint
For class-based logic, WebSocketEndpoint provides a structured way to handle events. It includes built-in decoding for common formats based on the encoding attribute.
| Method | Description |
|---|---|
on_connect(websocket) | Called when the client connects; default implementation calls accept(). |
on_receive(websocket, data) | Called when a message is received; data is decoded based on encoding. |
on_disconnect(websocket, close_code) | Called when the connection is closed. |
Sources: starlette/endpoints.py:59-123
Data Handling Methods
The WebSocket class provides helper methods for different data types:
| Data Type | Receive Method | Send Method | Iteration Method |
|---|---|---|---|
| Text | receive_text() | send_text(data) | iter_text() |
| Bytes | receive_bytes() | send_bytes(data) | iter_bytes() |
| JSON | receive_json(mode) | send_json(data, mode) | iter_json() |
Sources: starlette/websockets.py:134-167
Testing WebSockets
Starlette's TestClient includes a WebSocketTestSession to simulate WebSocket interactions in a synchronous testing environment using a BlockingPortal.
def test_websocket_communication():
client = TestClient(app)
with client.websocket_connect("/") as websocket:
websocket.send_text("Hello")
data = websocket.receive_text()
assert data == "Message was: Hello"
Sources: starlette/testclient.py:90-110, tests/test_websockets.py:91-100
Error Handling
Starlette uses the WebSocketDisconnect exception to signal that a connection has been closed. This exception carries the closure code (e.g., 1000 for normal closure) and an optional reason.
- State Violations: Calling
receiveafter a disconnect orsendafter a close results in aRuntimeError. - Protocol Errors: Receiving an unexpected ASGI message type (e.g.,
websocket.receivebeforewebsocket.connect) raises aRuntimeError. - Disconnections: If the underlying transport fails during a
send, Starlette raisesWebSocketDisconnectwith code 1006 (Abnormal Closure).
Sources: starlette/websockets.py:20-24, starlette/websockets.py:46-56, starlette/websockets.py:78-82
Summary
WebSockets in Starlette provide a robust, state-aware interface for real-time applications. By abstracting the complex ASGI state transitions into a simple WebSocket object and providing high-level routing and endpoint classes, the framework enables efficient bidirectional communication while maintaining strict protocol compliance.