36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
from fastapi.responses import HTMLResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
from typing import List
|
|
from datetime import datetime
|
|
|
|
app = FastAPI()
|
|
|
|
with open("index.html", "r") as file:
|
|
html = file.read()
|
|
|
|
listaConnessioni: List[WebSocket] = [] #lista delle 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()
|
|
orario = datetime.now().strftime("%H:%M") #orario di quando e' stato inviato il messaggio
|
|
messaggio_con_orario = orario + " ---> " + data
|
|
|
|
for connection in listaConnessioni:
|
|
try:
|
|
await connection.send_text(messaggio_con_orario)
|
|
except Exception as e:
|
|
print("Errore nell'invio dei dati a " + connection + ": " + e)
|
|
listaConnessioni.remove(connection)
|
|
except WebSocketDisconnect:
|
|
listaConnessioni.remove(websocket) |