Update main.py

master
leonardo_pcto 2025-06-16 12:48:21 +02:00
parent 80d3c3c5e6
commit febcb92d01
1 changed files with 18 additions and 5 deletions

19
main.py
View File

@ -1,19 +1,32 @@
from fastapi import FastAPI, WebSocket
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from typing import List
app = FastAPI()
with open("index.html", "r") as file:
html = file.read()
listaConnessioni: List[WebSocket] = [] # Lista di connessioni
@app.get("/")
async def get():
return HTMLResponse(html)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
listaConnessioni.append(websocket) # Aggiungo il websocket
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(data)
for connection in listaConnessioni:
try:
await connection.send_text(data)
except Exception as e:
print("Errore nell'invio dei dati a"+ connection + e)
listaConnessioni.remove(connection)
except WebSocketDisconnect:
listaConnessioni.remove(websocket)