Spaces:
Paused
Paused
Upload main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, WebSocket
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
|
| 4 |
+
app = FastAPI()
|
| 5 |
+
|
| 6 |
+
# Allow CORS for local development
|
| 7 |
+
app.add_middleware(
|
| 8 |
+
CORSMiddleware,
|
| 9 |
+
allow_origins=["*"],
|
| 10 |
+
allow_credentials=True,
|
| 11 |
+
allow_methods=["*"],
|
| 12 |
+
allow_headers=["*"],
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
connected_clients = []
|
| 16 |
+
|
| 17 |
+
@app.websocket("/ws")
|
| 18 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 19 |
+
await websocket.accept()
|
| 20 |
+
connected_clients.append(websocket)
|
| 21 |
+
try:
|
| 22 |
+
while True:
|
| 23 |
+
data = await websocket.receive_text()
|
| 24 |
+
for client in connected_clients:
|
| 25 |
+
if client != websocket:
|
| 26 |
+
await client.send_text(data)
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"Client disconnected: {e}")
|
| 29 |
+
finally:
|
| 30 |
+
connected_clients.remove(websocket)
|