| 1 |
from typing import Any, AsyncGenerator |
| 2 |
|
| 3 |
import anyio |
| 4 |
|
| 5 |
from litestar import Litestar, WebSocket, websocket |
| 6 |
from litestar.exceptions import WebSocketDisconnect |
| 7 |
from litestar.handlers import send_websocket_stream |
| 8 |
|
| 9 |
|
| 10 |
@websocket("/") |
| 11 |
async def handler(socket: WebSocket) -> None: |
| 12 |
await socket.accept() |
| 13 |
should_stop = anyio.Event() |
| 14 |
|
| 15 |
async def handle_stream() -> AsyncGenerator[str, None]: |
| 16 |
while not should_stop.is_set(): |
| 17 |
await anyio.sleep(0.5) |
| 18 |
yield "ping" |
| 19 |
|
| 20 |
async def handle_receive() -> Any: |
| 21 |
await socket.send_json({"handle_receive": "start"}) |
| 22 |
async for event in socket.iter_json(): |
| 23 |
await socket.send_json(event) |
| 24 |
|
| 25 |
try: |
| 26 |
async with anyio.create_task_group() as tg: |
| 27 |
tg.start_soon(send_websocket_stream, socket, handle_stream()) |
| 28 |
tg.start_soon(handle_receive) |
| 29 |
except WebSocketDisconnect: |
| 30 |
should_stop.set() |
| 31 |
|
| 32 |
|
| 33 |
app = Litestar([handler]) |