Update main.py
parent
80d3c3c5e6
commit
febcb92d01
23
main.py
23
main.py
|
|
@ -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()
|
||||
while True:
|
||||
data = await websocket.receive_text()
|
||||
await websocket.send_text(data)
|
||||
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)
|
||||
Loading…
Reference in New Issue