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.responses import HTMLResponse
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from typing import List
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
with open("index.html", "r") as file:
|
with open("index.html", "r") as file:
|
||||||
html = file.read()
|
html = file.read()
|
||||||
|
|
||||||
|
listaConnessioni: List[WebSocket] = [] # Lista di connessioni
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
async def get():
|
async def get():
|
||||||
return HTMLResponse(html)
|
return HTMLResponse(html)
|
||||||
|
|
||||||
|
|
||||||
@app.websocket("/ws")
|
@app.websocket("/ws")
|
||||||
async def websocket_endpoint(websocket: WebSocket):
|
async def websocket_endpoint(websocket: WebSocket):
|
||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
while True:
|
listaConnessioni.append(websocket) # Aggiungo il websocket
|
||||||
data = await websocket.receive_text()
|
|
||||||
await websocket.send_text(data)
|
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