【问题标题】:Django Channels Consumer Not Connecting to websocketDjango Channels Consumer 未连接到 websocket
【发布时间】:2022-01-12 13:56:54
【问题描述】:

我在客户端创建了一个带有 javascripts 的 websocket...然后按照以下方式设置我的项目以处理 webocket 连接(遵循官方 django-channels 文档)。但是每次我刷新页面并从浏览器控制台观看 websocket 时......它都会失败。我在消费者类的 init 中插入了一个打印语句并打印了它(每次访问或刷新包含 websocket 的页面时)......这意味着路由工作正常......但是由于某些原因,消费者没有按预期连接/接受与 websocket 的连接。再次,开发服务器中没有关于任何 websocket 连接过程的日志。请任何人帮助并提出修复建议。

python 版本 - 3.9.9, django 版本 - 3.2.9, 频道版本 - 3.0.4

我的setting.py文件(相关行)
INSTALLED_APPS = [
    ...
    'channels',
]


ASGI_APPLICATION = 'ma_mall.asgi.application'

CHANNEL_LAYERS = {
    "default": {
        'BACKEND': "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            'hosts': [('127.0.0.1', 6379)],
        }
    }
}

我的 asgi.py 文件
application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(
            routing.websocket_urlpatterns            
        )
})

我的 routing.py 文件

websocket_urlpatterns = [
    path("ws/notifications/", consumers.NotificationConsumer.as_asgi()),
]
我的消费者档案
class NotificationConsumer(AsyncJsonWebsocketConsumer):
    groups = ['general_group']

    async def connect(self):
        await self.accept()
        await self.channel_layer.group_add('notification_group', self.channel_name)
        await self.channel_layer.group_send('notification_group', 
            {
                'type': 'tester.message',
                'tester': 'tester'
            }
        )
        
    async def disconnect(self, close_code):
        await self.channel_layer.group_discard('notification_group', self.channel_name)

客户端 websocket 的 javascript

我在客户端使用 javascript 创建为 websocket,如下所示

       const notification_websocket = new WebSocket(
            'ws://' +
            window.location.host +
            '/ws/notifications/'
        );

        notification_websocket.onmessage = function (e) {
            let data = JSON.parse(e.data);
            console.log("Just received this from the back end.. 0", data);
        }

        notification_websocket.onclose = function (e) {
            console.log("websocket closed");
        }

【问题讨论】:

  • redis服务器是否运行并安装了redis包?
  • 是的...它已安装并正在运行

标签: python-3.x django websocket django-channels django-3.2


【解决方案1】:

我意识到我使用了旧版本的 Redis(在 Windows 上使用 redis),而问题恰好来自配置的 redis 部分。一旦我从使用 Redis 切换到使用 Memcache

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    }
}

websocket-consumer 连接已连接并按预期保持打开...我希望找到在 Windows 上使用 Redis 较新版本进行开发的解决方案

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 2021-07-03
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2021-07-24
    • 2020-06-26
    相关资源
    最近更新 更多