43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
from fastapi.responses import HTMLResponse
|
|
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
|
|
|
|
messaggi_salvati: List[str] = [] #memorizzo tutti i messaggi
|
|
|
|
@app.get("/")
|
|
async def get():
|
|
return HTMLResponse(html)
|
|
|
|
@app.websocket("/ws")
|
|
async def websocket_endpoint(websocket: WebSocket):
|
|
await websocket.accept()
|
|
listaConnessioni.append(websocket)
|
|
|
|
for messaggio in messaggi_salvati:
|
|
await websocket.send_text(messaggio)
|
|
|
|
try:
|
|
while True:
|
|
data = await websocket.receive_text()
|
|
orario = datetime.now().strftime("%H:%M")
|
|
messaggio_con_orario = orario + "---> " + data
|
|
|
|
messaggi_salvati.append(messaggio_con_orario)
|
|
|
|
for connection in listaConnessioni:
|
|
try:
|
|
await connection.send_text(messaggio_con_orario)
|
|
except Exception as e:
|
|
print("Errore nell'invio a " + connection + e)
|
|
listaConnessioni.remove(connection)
|
|
|
|
except WebSocketDisconnect:
|
|
listaConnessioni.remove(websocket) |