Search code examples
djangodjango-channelsdaphne

How to gracefully handle auto disconnect of Daphne websockets


Daphne has a parameter --websocket_timeout link. As mentioned in the doc,

--websocket_timeout WEBSOCKET_TIMEOUT
                 
Maximum time to allow a websocket to be connected. -1 for infinite.

The socket is disconnected and no further communication can be done. However, the client does not receives a disconnect event, hence cant handle it gracefully. How does my client get to know whether the socket is disconnected or not?? I don't want to keep (at client) a timer nor want to keep rechecking it.

This is how I deploy my app

daphne -b 0.0.0.0 -p 8000 --websocket_timeout 1800 app.asgi:application

The socket gets auto-disconnected after every 30 mins, but the client never gets to know about this.

Whats the right way to go about it,.??

Update

Trying to send an event before the connection is closed. I'm over-riding my websocket_disconnect handler that sends the json before disconnecting. However, it does not send the event.

class Consumer(AsyncJsonWebsocketConsumer):
    async def websocket_disconnect(self, message):
            """Over-riding."""
            print('Inside websocket_disconnect consumer')
            await self.send_json(
                "event": "disconnecting..."
            )
            await super().websocket_disconnect(message)

Solution

  • I'm not sure it's a problem that needs a solution. The client has a certainty that after X minutes of inactivity it will get disconnected, where X is determined by the server. It has no certainty it won't happen before that. So you need connectivity handling code regardless.

    While it seems dirty to keep an idling connection around, I can't imagine it costing a lot of resources.

    Your premise that the client doesn't get to know about it is wrong. When you register the onclose handler, the client receives a disconnect event and can act accordingly.