mirror of
https://github.com/dcs-retribution/dcs-retribution.git
synced 2025-11-10 15:41:24 +00:00
All multiple event steam connections.
We don't support multi-client yet, but this is useful when debugging the react UI in a browser instead of in the Liberation UI.
This commit is contained in:
parent
781f8fb0e8
commit
d53fc46ffc
@ -1,6 +1,7 @@
|
||||
from fastapi import APIRouter
|
||||
from asyncio import wait
|
||||
|
||||
from fastapi import APIRouter, WebSocket
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from starlette.websockets import WebSocket
|
||||
|
||||
from .eventstream import EventStream
|
||||
from .models import GameUpdateEventsJs
|
||||
@ -9,17 +10,42 @@ from .. import GameContext
|
||||
router: APIRouter = APIRouter()
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
def __init__(self) -> None:
|
||||
self.active_connections: list[WebSocket] = []
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
futures = []
|
||||
for connection in self.active_connections:
|
||||
futures.append(connection.close())
|
||||
await wait(futures)
|
||||
|
||||
async def connect(self, websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
self.active_connections.append(websocket)
|
||||
|
||||
def disconnect(self, websocket: WebSocket) -> None:
|
||||
self.active_connections.remove(websocket)
|
||||
|
||||
async def broadcast(self, events: GameUpdateEventsJs) -> None:
|
||||
futures = []
|
||||
for connection in self.active_connections:
|
||||
futures.append(connection.send_json(jsonable_encoder(events)))
|
||||
await wait(futures)
|
||||
|
||||
|
||||
manager = ConnectionManager()
|
||||
|
||||
|
||||
@router.websocket("/eventstream")
|
||||
async def event_stream(websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
await manager.connect(websocket)
|
||||
while True:
|
||||
if not (events := await EventStream.get()).empty:
|
||||
if events.shutting_down:
|
||||
await websocket.close()
|
||||
await manager.shutdown()
|
||||
return
|
||||
|
||||
await websocket.send_json(
|
||||
jsonable_encoder(
|
||||
GameUpdateEventsJs.from_events(events, GameContext.get())
|
||||
)
|
||||
await manager.broadcast(
|
||||
GameUpdateEventsJs.from_events(events, GameContext.get())
|
||||
)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user