I messaggi della chat vengono memorizzati
parent
bfb517a2f3
commit
4ad10a1b4c
17
main.py
17
main.py
|
|
@ -1,6 +1,5 @@
|
||||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
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
|
from typing import List
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
@ -11,6 +10,8 @@ with open("index.html", "r") as file:
|
||||||
|
|
||||||
listaConnessioni: List[WebSocket] = [] #lista delle connessioni
|
listaConnessioni: List[WebSocket] = [] #lista delle connessioni
|
||||||
|
|
||||||
|
messaggi_salvati: List[str] = [] #memorizzo tutti i messaggi
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
async def get():
|
async def get():
|
||||||
return HTMLResponse(html)
|
return HTMLResponse(html)
|
||||||
|
|
@ -18,19 +19,25 @@ async def get():
|
||||||
@app.websocket("/ws")
|
@app.websocket("/ws")
|
||||||
async def websocket_endpoint(websocket: WebSocket):
|
async def websocket_endpoint(websocket: WebSocket):
|
||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
listaConnessioni.append(websocket) #aggiungo il websocket
|
listaConnessioni.append(websocket)
|
||||||
|
|
||||||
|
for messaggio in messaggi_salvati:
|
||||||
|
await websocket.send_text(messaggio)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
data = await websocket.receive_text()
|
data = await websocket.receive_text()
|
||||||
orario = datetime.now().strftime("%H:%M") #orario di quando e' stato inviato il messaggio
|
orario = datetime.now().strftime("%H:%M")
|
||||||
messaggio_con_orario = orario + " ---> " + data
|
messaggio_con_orario = orario + "---> " + data
|
||||||
|
|
||||||
|
messaggi_salvati.append(messaggio_con_orario)
|
||||||
|
|
||||||
for connection in listaConnessioni:
|
for connection in listaConnessioni:
|
||||||
try:
|
try:
|
||||||
await connection.send_text(messaggio_con_orario)
|
await connection.send_text(messaggio_con_orario)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Errore nell'invio dei dati a " + connection + ": " + e)
|
print("Errore nell'invio a " + connection + e)
|
||||||
listaConnessioni.remove(connection)
|
listaConnessioni.remove(connection)
|
||||||
|
|
||||||
except WebSocketDisconnect:
|
except WebSocketDisconnect:
|
||||||
listaConnessioni.remove(websocket)
|
listaConnessioni.remove(websocket)
|
||||||
Loading…
Reference in New Issue