0

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)
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

1 Answers1

1

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.

  • The client does receive the event when the python app sends `return self.send({'close': True})`. However, no event is received when daphne auto-disconnects after 30 mins set via `--websocket_timeout 1800`. – Praful Bagai Nov 25 '20 at 12:37
  • I just tested it with that setting set to 30 seconds and 5 seconds, cause well, I got impatient :). Working as advertised. But I'm using Daphne 2.5.0 (haven't gotten around to dealing with BC issues). –  Nov 25 '20 at 13:56
  • Can I send an event before disconnecting?? Updating my code, pls have a look. – Praful Bagai Nov 26 '20 at 12:31
  • You're still assuming something is sent. I just did a `kill -KILL 9775`, where 9775 is the pid of daphne. That means daphne cannot send anything even it would want to, since KILL terminates abruptly. And the onclose() event fired. So maybe it's the browser. I'm using latest firefox on a Mac. –  Nov 26 '20 at 14:11
  • I get it now. Thank you so much for the help. – Praful Bagai Nov 28 '20 at 08:37