【发布时间】: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