Skip to content

Commit

Permalink
fix websocket disconnection error
Browse files Browse the repository at this point in the history
  • Loading branch information
mariemeSall committed Jan 30, 2024
1 parent f6a46a0 commit ae32d1b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
19 changes: 14 additions & 5 deletions api/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from fastapi import Depends, FastAPI, WebSocket
from fastapi import Depends, FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from datetime import datetime
from fastapi.websockets import WebSocketState
from fastapi_sqlalchemy import DBSessionMiddleware, db
from BDD.models import Coordonnee
from BDD.schema import Coordonnee as Model_coordonnee
Expand Down Expand Up @@ -44,13 +45,21 @@ async def add_coordonnees(coor: Model_coordonnee, connections= Depends(get_conne
db_coor = Coordonnee(latitude = coor.latitude, longitude = coor.longitude, ip = coor.ip, date = datetime.strptime(coor.date, date_format))
db.session.add(db_coor)
db.session.commit()
await connections[0].send_json({'latitude': coor.latitude, 'longitude':coor.longitude, 'ip': coor.ip, 'date': coor.date})

for i in range(len(connections)):
if connections[i].client_state == WebSocketState.DISCONNECTED :
connections.remove(connections[i])
else :
await connections[i].send_json({'latitude': coor.latitude, 'longitude':coor.longitude, 'ip': coor.ip, 'date': coor.date})
return True

@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket, connections = Depends(get_connections)):
await websocket.accept()
connections.append(websocket)
while True:
data = await websocket.receive_json()
await websocket.send_json(data)
try:
while True:
data = await websocket.receive_json()
await websocket.send_json(data)
except WebSocketDisconnect :
connections.remove(websocket)
2 changes: 1 addition & 1 deletion producer/producer.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def produce_messages(bootstrap_servers, topic, num_messages):
partition = get_machine_partition()
# partition = 0
producer.produce(topic, value=message, partition=partition, callback=delivery_report)
time.sleep(0.5)
time.sleep(5)

producer.flush()

Expand Down

0 comments on commit ae32d1b

Please sign in to comment.