首页 > 解决方案 > Django-channels 向组发送消息

问题描述

我正在编写一个需要使用套接字的应用程序。为了处理它,我使用 django 频道,但我无法将消息广播到群组。

class waiting(WebsocketConsumer): 
    def connect(self): 
        self.channel_layer.group_add( 'my_group_name', self.channel_name )

        if <condition>:
            self.channel_layer.group_send( # This does not give any effect. I'm sure the condition is satisfied.
                'my_group_name',
                {
                    'message' : 'succes'
                }
            )

        self.accept()
        self.send(json.dumps({'message' : 'message'})) # This works perfect

    def disconnect(self, close_code):
        self.channel_layer.group_discard(
            'my_group_name',
            self.channel_name
        )

我有什么错?我已经阅读了许多教程和文档,但我没有找到任何解决方案。我应该更改什么以使此代码按我的意愿工作?

我正在使用频道 == 2.3.1 和 Django 2.2.6。

标签: pythondjangowebsocketdjango-channels

解决方案


connect在广播之前,您实际上并没有接受函数中的连接。没有 self.accept() 连接将被拒绝并关闭。


推荐阅读