WebSocket support
aiohttp provides asynchronous WebSocket support for both sides of a connection. A client opens a WebSocket through ClientSession, while a server upgrades an HTTP request through WebSocketResponse; both sides then exchange typed messages over a shared protocol engine.
Capability model
The WebSocket API turns an HTTP connection into a long-lived, two-way message channel. The public surface covers connection setup, text and binary data, JSON helpers, control frames, heartbeats, size and receive limits, compression, and orderly close handling (aiohttp/client.py• L907-954, aiohttp/web_ws.py• L72-120).
The same message model is used on the client and server. Application code can consume messages with receive() or asynchronous iteration and can send text, bytes, JSON, ping, pong, or close data through the matching endpoint object (aiohttp/client_ws.py• L273-328, aiohttp/web_ws.py• L462-553).
| Capability | Client side | Server side |
|---|---|---|
| Open a connection | ClientSession.ws_connect() | WebSocketResponse.prepare(request) |
| Negotiate protocols | Offers requested sub-protocols | Selects the first supported common protocol |
| Exchange data | ClientWebSocketResponse | WebSocketResponse |
| Message forms | Text, binary, and JSON | Text, binary, and JSON |
| Connection health | Optional heartbeat and automatic pong handling | Optional heartbeat and automatic pong handling |
| End the session | Close handshake with a close timeout | Close handshake with a close timeout |
References: aiohttp/client.py• L907-954 aiohttp/client_ws.py• L273-328 aiohttp/web_ws.py• L72-120 aiohttp/web_ws.py• L462-553
Client connections
The client API creates a WebSocket from an existing ClientSession so that normal session concerns remain part of the connection flow. ws_connect() sends the WebSocket upgrade request and returns a ClientWebSocketResponse after the peer accepts it (aiohttp/client.py• L1008-1096).
The client checks the server response before it exposes the upgraded connection. It requires a switching-protocols response, the WebSocket upgrade markers, a valid challenge response, and a compatible negotiated protocol (aiohttp/client.py• L1099-1150). This keeps an ordinary HTTP response or a bad handshake from being mistaken for a live WebSocket.
References: aiohttp/client.py• L1008-1150 aiohttp/client_ws.py• L61-109
Server endpoints
The server API represents an upgraded request with WebSocketResponse. A handler can first call can_prepare() when it needs to decide whether the request is a valid WebSocket request, then call prepare() to complete the upgrade and start message processing (aiohttp/web_ws.py• L259-269, aiohttp/web_ws.py• L403-411).
After preparation, the HTTP request protocol routes incoming bytes to the WebSocket reader and turns off HTTP keep-alive for that connection. The handler uses the response object as the long-lived endpoint and closes it when the application session ends (aiohttp/web_ws.py• L355-401).
References: aiohttp/web_ws.py• L259-269 aiohttp/web_ws.py• L271-375 aiohttp/web_ws.py• L377-411
Handshake negotiation
The handshake changes the connection from HTTP framing to WebSocket framing. The client sends the upgrade request with a random key and optional sub-protocol and compression offers. The server validates the request, computes the acceptance value, and returns the selected options; the client then verifies that response (aiohttp/client.py• L1054-1077, aiohttp/web_ws.py• L271-353).
Sub-protocol selection is an application-level contract. The client offers an ordered collection of names, and the server selects the first offered name that it supports. If there is no overlap, the connection can still proceed without a selected sub-protocol (aiohttp/client.py• L1071-1074, aiohttp/web_ws.py• L289-307).
Compression is negotiated as the permessage-deflate extension. The shared helpers parse the peer offer and generate the response offer, including window-size and context-takeover settings. Control frames remain uncompressed (aiohttp/…/helpers.py• L67-148, aiohttp/…/writer.py• L73-121).
References: aiohttp/client.py• L1054-1150 aiohttp/web_ws.py• L271-353 aiohttp/…/helpers.py• L67-148
Message exchange
The protocol engine transforms byte frames into complete messages before the endpoint returns them to application code. A message carries a WSMsgType that distinguishes text, binary, ping, pong, close, and aiohttp connection states; text can be returned as decoded text or as raw bytes (aiohttp/…/models.py• L27-39, aiohttp/…/models.py• L42-149). The reader keeps the same framing contract in its Python and compiled forms (aiohttp/…/reader_py.py• L35-71, aiohttp/_websocket/reader_c.pxd#L6-L132).
The reader accepts fragmented data messages and assembles them before delivery. It validates reserved bits, opcodes, masking, control-frame limits, close codes, UTF-8 text, compression, and the configured maximum message size (aiohttp/…/reader_py.py• L275-427, aiohttp/…/reader_py.py• L429-658). Control frames cannot carry per-message compression. The reader rejects an oversized declared data frame before it buffers the payload, and it limits the number of stored fragments so a peer cannot use many small fragments to grow memory without bound (aiohttp/…/reader_py.py• L491-529, aiohttp/…/reader_py.py• L564-618).
The endpoint hides protocol control traffic by default. Automatic ping and pong handling keeps health checks out of the application message loop, while close and error messages move the endpoint into its closing or closed state (aiohttp/client_ws.py• L384-457, aiohttp/web_ws.py• L620-693).
This diagram shows how an HTTP request becomes an application message stream and how control events end that stream.
flowchart LR
A[HTTP upgrade request] --> B{Handshake accepted?}
B -- No --> C[HTTP or handshake error]
B -- Yes --> D[Upgraded transport]
D --> E[Frame reader]
E --> F[Validation and reassembly]
F --> G[Typed message queue]
G --> H[Client or server endpoint]
H --> I[Application data]
E --> J[Ping, pong, or close]
J --> K[Automatic control handling]
K --> L[Closing or closed endpoint]
References: aiohttp/…/models.py• L27-149 aiohttp/…/reader_py.py• L275-427 aiohttp/…/reader_c.pxd• L49-132 aiohttp/client_ws.py• L400-476 aiohttp/web_ws.py• L620-693
Flow control and connection health
The shared data queue links protocol parsing to the asyncio transport. It pauses transport reads when queued message data exceeds its high-water limit, and the reader also holds unparsed input while the application drains queued messages. It resumes parsing at a lower water mark before it resumes transport reads. This keeps both the message queue and the parser's pending input within a bounded range (aiohttp/…/reader_py.py• L81-187, aiohttp/…/reader_py.py• L429-446, aiohttp/…/reader_py.py• L657-658). The endpoint owns the parser while the connection can still be drained, so this paused state does not depend on an accidental reference from the transport (aiohttp/client_ws.py• L77-86, aiohttp/web_ws.py• L377-401).
Heartbeat support sends periodic ping frames and expects a pong within the heartbeat window. A missed pong marks the connection as abnormally closed and reports the failure to a waiting receiver. Incoming data resets the heartbeat timer, with resets grouped within one event-loop turn to avoid needless timer work (aiohttp/client_ws.py• L129-223, aiohttp/web_ws.py• L142-249).
References: aiohttp/…/reader_py.py• L81-187 aiohttp/…/reader_py.py• L429-446 aiohttp/…/reader_c.pxd• L49-70 aiohttp/client_ws.py• L77-86 aiohttp/client_ws.py• L129-233 aiohttp/web_ws.py• L142-249 aiohttp/web_ws.py• L377-401
Frame output
The shared writer turns application payloads into WebSocket frames and applies the side-specific masking rule, optional permessage-deflate, and transport back-pressure. Control frames bypass compression, while compressed sends are serialized so a shared compression context cannot be advanced by one send and then observed by another (aiohttp/…/writer.py• L26-37, aiohttp/…/writer.py• L74-129, aiohttp/…/writer.py• L131-179).
Large compressed messages may yield while they are processed. The writer protects the full compression-and-send operation from cancellation, which keeps the wire stream and compression state aligned when application tasks overlap or stop (aiohttp/…/writer.py• L84-117, aiohttp/…/writer.py• L226-258).
References: aiohttp/…/writer.py• L26-37 aiohttp/…/writer.py• L74-129 aiohttp/…/writer.py• L131-258
Endpoint lifecycles
Client and server endpoints share the same broad lifecycle: handshake, prepared or open, closing, and closed. They prevent concurrent receives, expose close codes, translate end-of-stream and protocol errors into WebSocket results, and use asynchronous context management to help release the connection (aiohttp/client_ws.py• L320-367, aiohttp/client_ws.py• L384-457, aiohttp/web_ws.py• L529-589, aiohttp/web_ws.py• L620-798).
See WebSocket endpoint lifecycles for the client and server state transitions, close behavior, and shutdown paths.
References: aiohttp/client_ws.py• L331-384 aiohttp/client_ws.py• L400-579 aiohttp/web_ws.py• L529-589 aiohttp/web_ws.py• L620-798
Protocol engine
The shared protocol engine owns frame parsing, message assembly, masking, payload limits, compression, and frame writing. Client and server endpoint classes provide the API and lifecycle rules around this engine; they do not define a separate wire format for each side (aiohttp/http_websocket.py• L1-59, aiohttp/…/reader.py• L1-31, aiohttp/…/writer.py• L39-76).
See WebSocket protocol engine for the frame and message rules that apply after the handshake.
References: aiohttp/http_websocket.py• L1-59 aiohttp/…/reader.py• L1-31 aiohttp/…/reader_py.py• L190-658 aiohttp/…/reader_c.pxd• L71-132 aiohttp/…/writer.py• L40-269
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to handshake headers or acceptance checks must stay aligned between
ClientSession._ws_connect()andWebSocketResponse._handshake(). - Changes to negotiated compression settings must preserve the client and server meanings of window size and context takeover.
- Changes to
WSMsgTypeor message models must preserve the receive behavior of both endpoint classes and their typed helper methods. - Changes to queue limits, parser stalling, or parser ownership must preserve back-pressure on both client and server transports without losing the pending input tail.
- Changes to compressed frame sending must preserve serialization and cancellation safety for the shared compression context.
- Changes to close or heartbeat handling must preserve wake-up behavior for tasks waiting in
receive(). - Changes to reserved-bit validation must keep control-frame rules aligned with compression handling and protocol-error close behavior.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Missing or invalid upgrade headers | The server rejects the request as a bad HTTP request. | Validate the upgrade and connection headers before prepare(). |
| Non-101 response or invalid challenge | The client raises a WebSocket handshake error and closes the HTTP response. | Check status, upgrade state, and acceptance key together. |
| Invalid frame structure, reserved bits, close code, or UTF-8 text | The reader reports a protocol error and the endpoint closes with the related code. | Keep frame validation and message-size checks enabled. |
| Message data exceeds the configured limit | The connection receives a message-too-big error. | Set max_msg_size for the expected application payloads. |
| No pong arrives after a heartbeat ping | The endpoint records abnormal closure and wakes a waiting receiver with the failure. | Use a heartbeat suited to the peer and network path. |
More than one task calls receive() at once | The endpoint raises a runtime error. | Assign one receive loop to each WebSocket endpoint. |
| The application stops draining a busy endpoint | The parser and transport pause at their high-water limits instead of accepting unbounded input. | Keep a receive loop active while the connection is open. |
| A large compressed send is cancelled while it is in progress | The caller can stop waiting, but the protected send continues so the wire stream and compression state stay aligned. | Do not treat caller cancellation as proof that the send has stopped. |
Key files
| File | Why to read it |
|---|---|
| aiohttp/client.py | Shows the client entry point and the request and response handshake flow. |
| aiohttp/client_ws.py | Shows the client message API, control handling, heartbeat behavior, and close lifecycle. |
| aiohttp/web_ws.py | Shows the server upgrade, endpoint API, control handling, heartbeat behavior, and close lifecycle. |
| aiohttp/http_websocket.py | Defines the shared public protocol symbols and connects endpoint code to the shared engine. |
| aiohttp/…/models.py | Defines message kinds and close codes used by both sides. |
| aiohttp/…/reader_py.py | Explains the wire-to-message path, its validation boundaries, and its back-pressure behavior. |
aiohttp/_websocket/reader_c.pxd | Shows the typed reader and queue contract used by the compiled reader path. |
| aiohttp/…/writer.py | Explains the message-to-wire path, masking, compression, cancellation safety, and transport flow control. |
| aiohttp/http_parser.py | Shows how HTTP parsing detects the upgrade and switches the connection to upgraded mode. |