在youtube上关注这些教程之一 我刚刚使用django-channels编写了一个websocket服务器 这是我的代码 signal.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
@receiver(post_save, sender=User)
def announce_new_user(sender, instance, created, **kwargs):
if created:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
"gossip", {"type": "user_gossip",
"event": "New User",
"username": instance.username})
consumers.py
from channels.generic.websocket import AsyncJsonWebsocketConsumer
class NoseyConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
await self.channel_layer.group_add("gossip", self.channel_name)
print(f"Added {self.channel_name} channel to gossip")
async def disconnect(self, close_code):
await self.channel_layer.group_discard("gossip", self.channel_name)
print(f"Removed {self.channel_name} channel to gossip")
async def user_gossip(self, event):
await self.send_json(event)
print(f"Got message {event} at {self.channel_name}")
apps.py
from django.apps import AppConfig
class NotifierConfig(AppConfig):
name = 'notifier'
def ready(self):
from .import signals
初始化 .py
default_app_config = 'notifier.apps.NotifierConfig'
routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from notifier.consumers import NoseyConsumer
application = ProtocolTypeRouter({
"websocket": URLRouter([
path("notifications/", NoseyConsumer),
])
})
以及settings.py
中的channel_layersCHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost",16379)],
},
},
}
我不知道问题是什么,当我使用admin创建新用户时,我看不到通过控制台从django websockets传输的任何数据,并且尝试了很多方法来找出问题,但仍然没有用
这是我的客户javascript代码
<html>
<head>
<script type = "text/javascript">
// Let us open a web socket
var ws = new WebSocket("ws://localhost:8000/notifications/");
var msg = "hi, this is simple message.";
ws.onopen = function(evt) {
ws.send(msg);
};
ws.onmessage = function(evt) {
// handle this message
console.log(evt.username);
};
ws.onclose = function(evt) {
// this channel is closed
};
ws.onerror = function(evt) {
// handle this error
};
</script>
</head>
<body>
</body>
</html>
当我尝试通过在此处添加用户的方式来访问同一网站时,我在终端机中获得的信息
HTTP GET / 200 [0.01, 127.0.0.1:55829]
WebSocket HANDSHAKING /notifications/ [127.0.0.1:55935]
WebSocket CONNECT /notifications/ [127.0.0.1:55935]
Added specific.pgRlAson!hqgpORLfvfbO channel to gossip
Exception inside application: Expecting value: line 1 column 1 (char 0)
File "C:\Users\madhumani\workspace\ven\lib\site-packages\channels\consumer.py", line 59, in __call__
[receive, self.channel_receive], self.dispatch
File "C:\Users\madhumani\workspace\ven\lib\site-packages\channels\utils.py", line 52, in await_many_dispatch
await dispatch(result)
File "C:\Users\madhumani\workspace\ven\lib\site-packages\channels\consumer.py", line 73, in dispatch
await handler(message)
File "C:\Users\madhumani\workspace\ven\lib\site-packages\channels\generic\websocket.py", line 196, in websocket_
receive
await self.receive(text_data=message["text"])
File "C:\Users\madhumani\workspace\ven\lib\site-packages\channels\generic\websocket.py", line 259, in receive
await self.receive_json(await self.decode_json(text_data), **kwargs)
File "C:\Users\madhumani\workspace\ven\lib\site-packages\channels\generic\websocket.py", line 277, in decode_jso
n
return json.loads(text_data)
File "c:\users\madhumani\appdata\local\programs\python\python36-32\Lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "c:\users\madhumani\appdata\local\programs\python\python36-32\Lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "c:\users\madhumani\appdata\local\programs\python\python36-32\Lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
Expecting value: line 1 column 1 (char 0)
WebSocket DISCONNECT /notifications/ [127.0.0.1:55935]
答案 0 :(得分:0)
问题是您发送的事件没有匹配的接收者来处理。
您发送类型为user.gossip
的事件,而处理程序的名称为user_gossip
。事件类型和方法名称应该匹配,因此您可能需要将事件类型更改为user_gossip