Overview
WebSocket support is provided via thewsprotolibrary. Install the extra:
uv add "bengal-pounce[ws]"
Pounce supports:
- Standard WebSocket — Upgrade from HTTP/1.1
- WebSocket over HTTP/2 — Multiplexed with other HTTP/2 streams
- Per-message compression — Via the permessage-deflate extension
ASGI WebSocket Lifecycle
WebSocket connections follow the ASGI WebSocket spec:
stateDiagram-v2
[*] --> Connect: websocket.connect
Connect --> Accepted: websocket.accept
Connect --> Rejected: websocket.close
Rejected --> [*]
Accepted --> Messaging: ready
Messaging --> Messaging: websocket.receive / websocket.send
Messaging --> Disconnected: websocket.disconnect
Disconnected --> [*]
- Connect —
websocket.connectevent received - Accept/Reject — App sends
websocket.acceptorwebsocket.close - Messages — Bidirectional
websocket.receiveandwebsocket.send - Disconnect —
websocket.disconnectevent
async def websocket_app(scope, receive, send):
assert scope["type"] == "websocket"
# Wait for connection
event = await receive()
assert event["type"] == "websocket.connect"
# Accept the connection
await send({"type": "websocket.accept"})
# Echo messages
while True:
event = await receive()
if event["type"] == "websocket.disconnect":
break
await send({
"type": "websocket.send",
"text": event.get("text", ""),
})
WebSocket over HTTP/2
When bothpounce[h2] and pounce[ws]are installed, WebSocket connections can be established over HTTP/2 using the extended CONNECT method (RFC 8441). This allows WebSocket streams to be multiplexed with regular HTTP/2 requests on the same connection.
Configuration
WebSocket connections respect the same timeout and limit settings as HTTP connections:
| Setting | Applies To |
|---|---|
keep_alive_timeout |
Idle WebSocket connections |
max_connections |
Total connections (HTTP + WebSocket) |
shutdown_timeout |
Graceful close during shutdown |
See Also
- HTTP/1.1 — WebSocket upgrade source
- HTTP/2 — WebSocket over H2
- API Reference — ASGI type definitions