4

It's been 1 month since I started using django-channels and now I have a feeling that I am not disconnecting websockets properly. When I disconnect I want to destroy the group completely if no one is there and it should be no sign of existence. When I'm rejecting connections I raise channels.exceptions.DenyConnection or send {'accepted': 'False'} I was just wondering if this is the right way to do things that I've mentioned or not.

ArminMz
  • 325
  • 6
  • 9

2 Answers2

9

Try calling self.close()

From the channels Documentation:

class MyConsumer(WebsocketConsumer):

    def connect(self):
        # Called on connection.
        # To accept the connection call:
        self.accept()
        # Or accept the connection and specify a chosen subprotocol.
        # A list of subprotocols specified by the connecting client
        # will be available in self.scope['subprotocols']
        self.accept("subprotocol")
        # To reject the connection, call:
        self.close()
Anatol
  • 3,720
  • 2
  • 20
  • 40
  • 6
    One thing I've noticed is that if you `close` before doing `accept`, any close-code is not sent to the client. `accept` is needed before closing for the code to be sent - seems like a mistake to me? – Silversonic Sep 12 '20 at 16:30
2

As far as I've understood this, the way to close a group is by using group_discard.

def disconnect(self, close_code):
    async_to_sync(self.channel_layer.group_discard)("yourgroupname", self.channel_name)

Without having tested this, I would assume that raising an exception would result in an error 500 at the client. And a client receiving an error would probably interpret that not as "closed normally".

See channel docs here: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#groups

normic
  • 1,388
  • 3
  • 24
  • 36