django websockets 无法在通道上发送消息

django websockets cannot dispatch message on channel

我在 Django 上使用带有 Redis 的网络套接字。 Django 在 macOS 服务器上 运行 很好,但我在 Redhat Linux 服务器上启动了 运行 它,现在每当我通过 websockets 发送包时,服务器都会给我这个错误:

ERROR - server - HTTP/WS send decode error:
    Cannot dispatch message on channel
    u'daphne.response.fzdRCEVZkh!nqhIpaLfWb' (unknown)

注意:虽然我收到错误,但包裹会正确收到。

我找不到关于这个错误的任何资源。

我关注了 official instructions 频道。

根据 Andrew Godwin(频道包的开发者)的说法,当您的频道已断开连接但未从频道组中删除时,会记录此消息:

Ah yes, that's Daphne being a little bit more verbose than before, I need to remove that. Don't worry about it - it's perfectly normal after you disconnect a channel that's still in a group. You might want to add a Group.discard call in a disconnect handler to stop it, though.

Source.

我遇到了同样的错误,使用了 channels.generic.websockets.WebsocketConsumer 的自定义实现。在 disconnect 回调中清理群组中的频道后,消息消失了。

基于 class 的消费者的简短示例:假设您在建立连接时将客户端添加到名为 foo 的广播组。然后,在客户端断开连接时,从组中删除其频道:

from channels import Group
from channels.generic.websockets import JsonWebsocketConsumer

class MyConsumer(JsonWebsocketConsumer):

    groupname = 'foo'

    def connect(self, message, **kwargs):
        # send an accept or the connection will be dropped automatically
        self.message.reply_channel.send({"accept": True})
        # add the channel to the broadcast group
        Group(self.groupname).add(message.reply_channel)
        # do the rest of logic that should happen on connection established
        ...

    def disconnect(self, message, **kwargs):
        Group(self.groupname).discard(message.reply_channel)
        # do the rest of logic that should happen on disconnect
        ...