【问题标题】:django websockets cannot dispatch message on channeldjango websockets 无法在频道上发送消息
【发布时间】:2017-09-02 01:10:12
【问题描述】:
我在 Django 上使用带有 Redis 的 Web 套接字。 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 的频道。
【问题讨论】:
标签:
django
websocket
redis
django-channels
【解决方案1】:
根据 Andrew Godwin(频道包的开发者)的说法,当您的频道已断开连接但未从频道组中删除时,会记录此消息:
啊,是的,Daphne 比以前更冗长了,我需要删除它。不用担心 - 断开仍在组中的频道后,这是完全正常的。不过,您可能希望在断开连接处理程序中添加一个 Group.discard 调用来停止它。
Source.
我有同样的错误,使用自定义 impl channels.generic.websockets.WebsocketConsumer。在disconnect回调中从群组中清理频道后,消息消失了。
一个基于类的消费者的简短示例:假设您在建立连接时将客户端添加到名为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
...