如何拒绝和关闭 django-channels 2 中的连接?

Arm*_*nMz 1 python django disconnect websocket django-channels

自从我开始使用 django-channels 已经 1 个月了,现在我觉得我没有正确断开 websockets。当我断开连接时,如果没有人在那里,我想完全摧毁该组,并且它应该没有存在的迹象。当我拒绝连接时,我提出 channels.exceptions.DenyConnection 或发送 {'accepted': 'False'} 我只是想知道这是否是我提到的事情的正确方式。

Ana*_*tol 5

试试打电话 self.close()

从频道文档:

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()
Run Code Online (Sandbox Code Playgroud)

  • 我注意到的一件事是,如果您在执行“accept”之前“close”,则任何关闭代码都不会发送到客户端。在关闭之前需要“accept”才能发送代码 - 对我来说似乎是一个错误? (4认同)

nor*_*mic 2

据我了解,关闭组的方法是使用 group_discard。

def disconnect(self, close_code):
    async_to_sync(self.channel_layer.group_discard)("yourgroupname", self.channel_name)
Run Code Online (Sandbox Code Playgroud)

如果没有对此进行测试,我会假设引发异常会导致客户端出现错误 500。收到错误的客户端可能会将其解释为“正常关闭”。

请参阅此处的频道文档:https ://channels.readthedocs.io/en/latest/topics/channel_layers.html#groups