27 lines
756 B
Python
27 lines
756 B
Python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
|
|
connectedClients: set[WebSocket] = set()
|
|
|
|
|
|
async def notifyClients(profileId: int | None):
|
|
if not profileId:
|
|
profileId = 1
|
|
message = str(profileId)
|
|
for client in list(connectedClients):
|
|
try:
|
|
await client.send_text(message)
|
|
except Exception:
|
|
connectedClients.discard(client)
|
|
|
|
|
|
def registerWebsocket(app: FastAPI):
|
|
@app.websocket("/ws")
|
|
async def websocketEndpoint(websocket: WebSocket):
|
|
await websocket.accept()
|
|
connectedClients.add(websocket)
|
|
try:
|
|
while True:
|
|
await websocket.receive_text()
|
|
except WebSocketDisconnect:
|
|
connectedClients.discard(websocket)
|