Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
|
@@ -2,16 +2,16 @@ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
| 2 |
from fastapi.responses import HTMLResponse
|
| 3 |
from fastapi.templating import Jinja2Templates
|
| 4 |
from fastapi.staticfiles import StaticFiles
|
| 5 |
-
from
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
templates = Jinja2Templates(directory="templates")
|
| 9 |
|
| 10 |
-
#
|
| 11 |
rooms = {}
|
| 12 |
|
| 13 |
@app.get("/")
|
| 14 |
-
async def
|
| 15 |
return templates.TemplateResponse("index.html", {"request": request})
|
| 16 |
|
| 17 |
@app.websocket("/ws/{room_id}")
|
|
@@ -20,14 +20,13 @@ async def websocket_endpoint(websocket: WebSocket, room_id: str):
|
|
| 20 |
if room_id not in rooms:
|
| 21 |
rooms[room_id] = []
|
| 22 |
rooms[room_id].append(websocket)
|
| 23 |
-
|
| 24 |
try:
|
| 25 |
while True:
|
| 26 |
data = await websocket.receive_text()
|
| 27 |
-
#
|
| 28 |
-
for
|
| 29 |
-
if
|
| 30 |
-
await
|
| 31 |
except WebSocketDisconnect:
|
| 32 |
rooms[room_id].remove(websocket)
|
| 33 |
if not rooms[room_id]:
|
|
|
|
| 2 |
from fastapi.responses import HTMLResponse
|
| 3 |
from fastapi.templating import Jinja2Templates
|
| 4 |
from fastapi.staticfiles import StaticFiles
|
| 5 |
+
from fastapi import Request
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
templates = Jinja2Templates(directory="templates")
|
| 9 |
|
| 10 |
+
# Keep track of rooms and their connections
|
| 11 |
rooms = {}
|
| 12 |
|
| 13 |
@app.get("/")
|
| 14 |
+
async def index(request: Request):
|
| 15 |
return templates.TemplateResponse("index.html", {"request": request})
|
| 16 |
|
| 17 |
@app.websocket("/ws/{room_id}")
|
|
|
|
| 20 |
if room_id not in rooms:
|
| 21 |
rooms[room_id] = []
|
| 22 |
rooms[room_id].append(websocket)
|
|
|
|
| 23 |
try:
|
| 24 |
while True:
|
| 25 |
data = await websocket.receive_text()
|
| 26 |
+
# Broadcast to other clients in room
|
| 27 |
+
for conn in rooms[room_id]:
|
| 28 |
+
if conn != websocket:
|
| 29 |
+
await conn.send_text(data)
|
| 30 |
except WebSocketDisconnect:
|
| 31 |
rooms[room_id].remove(websocket)
|
| 32 |
if not rooms[room_id]:
|