Tutorial: Realtime with WebSockets¶
This tutorial adds a realtime channel to an existing Lilya app.
Goal¶
Expose one websocket endpoint and test it locally.
Step 1: Register a websocket route¶
from lilya.types import Receive, Scope, Send
from lilya.websockets import WebSocket
async def app(scope: Scope, receive: Receive, send: Send):
websocket = WebSocket(scope=scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_json({"message": "Hello, world!"}, mode="binary")
await websocket.close()
Step 2: Co-locate HTTP and websocket routes¶
Keep websocket routes in the same feature module when they share dependencies and permissions.
Step 3: Test handshake and message flow¶
Use the Test Client to validate connect, send, and close behavior.
Realtime flow¶
sequenceDiagram
participant C as Client
participant A as Lilya
participant W as WebSocket handler
C->>A: websocket.connect
A->>W: accept()
C->>W: message
W-->>C: response message
C->>W: close