, следуя одному из этих руководств на YouTube
я только что написал сервер websocket с использованием django-каналов
вот мой код
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
* INIT 1011 * .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),
])
})
и в channel_layers в settings.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost",16379)],
},
},
}
Я не знаю, в чем проблема, когда когда-либо создавая нового пользователя с помощью администратора, я не вижу никаких данных, которые передаются из веб-сокетов django через консоль, и много пытался выяснить проблему, но все равно бесполезно
вот мой клиентский код 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]