Client and server WebSocket lifecycles
Client and server WebSocket endpoints turn one HTTP connection into a long-lived message channel. Each endpoint performs the handshake, gives application code a message interface, maintains liveness when requested, and ends by completing the close exchange or cleaning up after a lost transport. Both sides rely on the common WebSocket protocol engine, while their endpoint wrappers manage the rules of their own HTTP integration. See WebSocket support for the wider feature view.
Connection establishment
Server upgrade
The server endpoint is WebSocketResponse in aiohttp/web_ws.py. It checks that the request asks for a WebSocket upgrade before it changes the HTTP response to status 101. The response can select a shared subprotocol and a shared compression extension. After the handshake, the HTTP request handler keeps the same transport but uses the WebSocket message path. The upgrade also removes the connection from HTTP keep-alive because the WebSocket now owns the transport.
The server handler normally follows this order:
- Create
WebSocketResponse. - Optionally use
can_prepare()to check the request without starting it. - Call
prepare(request)to complete the upgrade. - Read and send messages until the endpoint closes.
- Return the response after the connection is closed or the handler is stopped.
References: aiohttp/web_ws.py• L72-120 aiohttp/web_ws.py• L259-415 tests/test_web_websocket_functional.py• L310-338
Client upgrade
The client endpoint is ClientWebSocketResponse in aiohttp/client_ws.py. ClientSession.ws_connect() sends an HTTP request with the WebSocket upgrade fields, then accepts the connection only when the server returns a valid upgrade response. It checks the server challenge and records the selected subprotocol and compression settings before exposing the message interface.
After validation, the client changes the connection from HTTP response handling to WebSocket handling. It applies the WebSocket receive timeout to the connection and attaches the WebSocket parser and message queue to the existing protocol. The endpoint keeps ownership of the parser until the response is no longer being drained. A failed handshake closes the response so the connection does not remain in the session as an unusable resource.
References: aiohttp/client.py• L939-983 aiohttp/client.py• L1014-1102 aiohttp/client.py• L1104-1227 aiohttp/client_ws.py• L54-103
Protocol engine handoff
After either side completes the handshake, its HTTP protocol wrapper installs the WebSocket reader on the connection. The reader converts incoming frames into messages. The writer sends outgoing messages through the same transport. Any bytes that arrived with the handshake remain part of the WebSocket stream rather than becoming a new HTTP request.
The client protocol stores the WebSocket message queue and parser. The server protocol stores the parser and an optional data callback. When buffered bytes remain at the upgrade boundary, the protocol feeds them to the WebSocket reader after the handoff. This keeps data received with the HTTP upgrade in the same WebSocket stream.
The endpoint keeps ownership of the parser while the response can still drain buffered input. When the endpoint closes, it releases that parser state along with the transport resources. This release also covers heartbeat failure and a client-side connection error, where the normal close exchange cannot run.
This handoff is the boundary between endpoint lifecycle work and frame processing. Read WebSocket protocol engine for frame rules and message assembly.
This diagram shows the transition from an HTTP upgrade to application messages and then to connection cleanup.
flowchart LR
A[HTTP request] --> B{Valid WebSocket upgrade?}
B -- No --> C[HTTP error or normal response]
B -- Yes --> D[HTTP 101 response]
D --> E[WebSocket reader and writer]
E --> F[Application messages]
E --> G[Control messages]
F --> H[Close and transport cleanup]
G --> H
References: aiohttp/web_ws.py• L355-401 aiohttp/client.py• L1177-1227 aiohttp/client_proto.py• L232-245 aiohttp/web_protocol.py• L455-533
Message exchange
Application messages
Once the handoff is complete, application code uses the endpoint wrapper rather than the HTTP response body. It can send text, binary, or JSON data and can receive the matching message types. receive() also supports asynchronous iteration, so a handler can process messages until a close-related message ends the loop.
Only one receive operation can wait on an endpoint at a time. This keeps message order clear and prevents two application tasks from consuming the same incoming stream.
References: aiohttp/web_ws.py• L457-502 aiohttp/web_ws.py• L604-677 aiohttp/web_ws.py• L747-781 aiohttp/client_ws.py• L283-322 aiohttp/client_ws.py• L393-469 aiohttp/client_ws.py• L539-572
Control messages
Control messages carry connection state rather than application data. A ping asks the peer to prove that it is still responsive. A pong answers a ping. A close message starts the WebSocket close exchange. With automatic handling enabled, the endpoint answers pings and hides ping and pong messages from application code.
Applications can disable automatic control handling when they need to inspect or manage these messages themselves. They can also send explicit ping and pong messages through the endpoint wrapper.
References: aiohttp/http_websocket.py• L28-31 aiohttp/web_ws.py• L462-479 aiohttp/web_ws.py• L655-693 aiohttp/client_ws.py• L277-294 aiohttp/client_ws.py• L450-469 tests/test_web_websocket_functional.py• L664-775
Heartbeat monitoring
A heartbeat is a timed ping and pong check used to detect a peer that no longer responds. When configured, the client or server schedules a ping after a period without received data. The connection protocol reports incoming data to the endpoint so that the endpoint can reset this liveness window. The endpoint then starts a shorter wait for the pong and cancels that wait when data arrives or the connection closes.
If the pong does not arrive, the endpoint records the failure as an abnormal closure, releases parser state, and closes the transport. Closing the endpoint also cancels the heartbeat timers and any ping task, so liveness work cannot continue after the connection ends.
References: aiohttp/web_ws.py• L124-257 aiohttp/client_ws.py• L104-235 aiohttp/client.py• L1219-1227 aiohttp/web_protocol.py• L481-533 tests/test_web_websocket_functional.py• L960-997
Connection closure
Close handshake
close() marks the endpoint closed locally, sends a close message with a code and optional reason, then waits for the peer's close message when the connection can complete the exchange. If application code is waiting in receive(), the endpoint first wakes that operation so the close task and receive task do not wait on each other. A close timeout or write failure ends the exchange as an abnormal closure.
When a peer sends a close message, the endpoint enters the closing state. Automatic close handling sends the local close response and then ends the transport. With automatic close disabled, application code receives the close message and must decide when to call close().
This sequence shows the normal close exchange between two endpoint wrappers and the shared protocol engine.
sequenceDiagram
participant AppA as Endpoint A
participant Engine as Protocol engine
participant AppB as Endpoint B
AppA->>Engine: close(code, reason)
Engine-->>AppB: close message
AppB->>Engine: close response
Engine-->>AppA: close message
AppA->>AppA: mark closed
AppB->>AppB: mark closed
Engine-->>AppA: close transport
Engine-->>AppB: close transport
The close path is safe to call more than once. A later call does not send another close message after the endpoint is already closed.
References: aiohttp/web_ws.py• L520-603 aiohttp/web_ws.py• L655-693 aiohttp/client_ws.py• L324-376 aiohttp/client_ws.py• L455-469 aiohttp/…/writer.py• L252-261 tests/test_web_websocket_functional.py• L823-874
Transport loss
Transport loss is separate from a normal close handshake. End-of-stream becomes a closed message for the endpoint. A protocol error or other read failure records an error and drives the endpoint toward closure. The endpoint then stops heartbeat work and closes or releases its transport.
On the server, the HTTP protocol cancels the active request when the connection is lost or the server shuts down. It also ends the WebSocket parser so a pending message read can finish. On the client, the client protocol ends the WebSocket payload and wakes waiters with a connection error or a closed result. The client releases parser state directly when a connection error bypasses close(). These paths prevent an application task from waiting forever on a dead peer.
References: aiohttp/web_ws.py• L231-257 aiohttp/web_ws.py• L639-669 aiohttp/web_ws.py• L792-798 aiohttp/client_ws.py• L210-235 aiohttp/client_ws.py• L424-448 aiohttp/client_proto.py• L117-192 aiohttp/web_protocol.py• L423-453
Resource cleanup
Endpoint cleanup has three linked goals: stop new writes, cancel timers and pending tasks, and release the HTTP connection. The server disables HTTP keep-alive after a successful upgrade because the transport now belongs to the WebSocket. The client closes its HTTP response when the WebSocket ends, which returns the connection to the client connection manager or closes it when reuse is not possible. Both endpoints release parser state when the response can no longer drain input.
The endpoint state remains observable through closed, close_code, and exception(). These values distinguish a normal close from a timeout, protocol error, or lost transport without exposing the frame-level work that produced the result.
References: aiohttp/web_ws.py• L251-269 aiohttp/web_ws.py• L355-401 aiohttp/web_ws.py• L520-603 aiohttp/client.py• L1202-1227 aiohttp/client_ws.py• L215-242 aiohttp/client_ws.py• L324-376 aiohttp/client_proto.py• L93-110
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the client handshake checks aligned with the server response fields. A change to status, upgrade, challenge, subprotocol, or extension negotiation can make one side reject a connection that the other side accepts.
- Keep the parser handoff aligned with buffered data handling. Bytes received before the WebSocket parser is installed must continue into the WebSocket stream after a successful upgrade.
- Keep heartbeat callback wiring aligned with the protocol wrapper. The callback must reset liveness on received data without restoring the old HTTP read-timeout behavior.
- Keep close-state transitions aligned with receive waiters. A close from another task must wake a pending receive before it waits for the peer's close message.
- Keep endpoint cleanup aligned with transport ownership. Server request shutdown and client response closure must both stop timers and release the transport.
- Keep direct error cleanup aligned with parser ownership. A heartbeat or transport error that bypasses the normal close path must still release parser state.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Missing or invalid upgrade fields | The server returns an HTTP error or the client raises WSServerHandshakeError. | Validate the request before prepare() and validate the response before creating the client WebSocket endpoint. |
| A ping receives no pong | The endpoint records an abnormal closure, releases parser state, and closes the transport. | Configure heartbeat only when the peer can answer control messages and keep the receive path active. |
| The peer closes while application code receives | The endpoint enters the closing state and may return a close message or a closed message. | Let one task own receive() and call close() when automatic close handling is disabled. |
| The transport ends before a close exchange | Pending reads end with a closed result or connection error, and the client bypasses the normal close path. | Treat closed, close_code, and exception() as the final connection state. |
Two tasks call receive() at the same time | The second call raises RuntimeError. | Use one receive loop and pass messages to other application tasks through an application queue. |
| The peer does not answer the close message before the close timeout | The endpoint marks the close as abnormal and releases the transport. | Set a close timeout that matches the expected peer and network behavior. |
Key files
| File | Why to read it |
|---|---|
| aiohttp/client.py | Defines the client-side upgrade request, validates the server handshake, and installs WebSocket parsing on the client connection. |
| aiohttp/client_ws.py | Defines the client endpoint state machine for messages, heartbeat, close exchange, and response cleanup. |
| aiohttp/web_ws.py | Defines the server endpoint state machine from request upgrade through message handling and transport shutdown. |
| aiohttp/client_proto.py | Shows how a client connection switches from HTTP response parsing to WebSocket parsing and how transport loss reaches the endpoint. |
| aiohttp/web_protocol.py | Shows how the server request handler installs the WebSocket parser, forwards received-data signals, and cancels active work during connection loss or shutdown. |
| aiohttp/…/reader_py.py | Shows the common boundary that turns incoming WebSocket frames into queued messages. |
| aiohttp/…/writer.py | Shows the common boundary that sends data and control messages and marks the writer as closing. |