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