Skip to content

Commit

Permalink
fix: fix websocket disconnect errors (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
gounux committed Jul 31, 2024
1 parent 8c59d07 commit b4c4544
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions gischat/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,20 @@ async def connect(self, room: str, websocket: WebSocket) -> None:
self.connections[room].append(websocket)

def remove(self, room: str, websocket: WebSocket) -> None:
self.connections[room].remove(websocket)
if websocket in self.connections[room]:
self.connections[room].remove(websocket)

async def notify(self, room: str, message: str) -> None:
living_connections = []
while len(self.connections[room]) > 0:
# Looping like this is necessary in case a disconnection is handled
# during await websocket.send_text(message)
websocket = self.connections[room].pop()
await websocket.send_text(message)
living_connections.append(websocket)
try:
await websocket.send_text(message)
living_connections.append(websocket)
except WebSocketDisconnect:
logger.error("Can not send message to disconnected websocket")
self.connections[room] = living_connections

def get_nb_users(self, room: str) -> int:
Expand Down Expand Up @@ -180,7 +184,10 @@ async def websocket_endpoint(websocket: WebSocket, room: str) -> None:
logger.error("Invalid message in websocket")
continue
logger.info(f"Message in room '{room}': {message}")
await notifier.notify(room, json.dumps(jsonable_encoder(message)))
try:
await notifier.notify(room, json.dumps(jsonable_encoder(message)))
except WebSocketDisconnect:
logger.error("Can not send message to disconnected websocket")
except WebSocketDisconnect:
notifier.remove(room, websocket)
await notifier.notify_internal(room)
Expand Down

0 comments on commit b4c4544

Please sign in to comment.