32 lines
989 B
Python
32 lines
989 B
Python
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()
|
|
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) |