Django-Channel 中的聊天消息不广播

时间:2021-06-03 13:54:28

标签: python django django-channels channels

我正在使用 django-channels。我创建了一个消费者来广播消息。奇怪的是,打开2个窗口看到广播后,出现了下面的情况。

消息显示在上次刷新的窗口上(消息数与打开的窗口数一致)。但消息永远不会显示在其他窗口上。

频道==3.0.3

channels-redis==3.2.0

Django==3.2.3

下面是我的consumer.py

class EchoBroadcastConsumer(SyncConsumer):

def websocket_connect(self, event):
    self.room_name = 'broadcast'
    self.send({
        'type': 'websocket.accept',
    })
    async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name)
    print(f'[{self.channel_name}] - You are connected!')

def websocket_receive(self, event):
    print(f'[{self.channel_name}]- You are have received {event["text"]}')
    async_to_sync(self.channel_layer.group_send)(
        self.room_name,
        {
            'type': 'websocket.message',
            'text': event.get('text')
        }
    )

def websocket_message(self, event):
    print(f'[{self.channel_name}] - Message Sent {event["text"]}')
    self.send({
        'type': 'websocket.send',
        'text': event.get('text')
    })

def websocket_disconnect(self, event):
    print(f'[{self.channel_name}] - You are have Disconnected')
    async_to_sync(self.channel_layer.group_discard)(self.room_name, self.channel_name)

下面是我的前端(JS)

const url = 'ws:127.0.0.1:8000/ws' + window.location.pathname;
const ws = new WebSocket(url);

ws.onopen = function(event){
    console.log("Connection is Open");
}

ws.onmessage = function(event){
    console.log("Message is received");
    const ul = document.getElementById('chat_list');
    var li = document.createElement('li');
    li.append(document.createTextNode(event.data));
    ul.append(li);
   // var data = JSON.parse(event.data)
    //li.append(document.createTextNode(
     //   '['+ data.username+ ']:' + data.text
    //));
    ul.append(li);
}

ws.onclose = function(event){
    console.log("Connection is Closed");
}

ws.onerror = function(event){
    console.log("Something went wrong");
}

const message_form = document.getElementById('message_form');
message_form.addEventListener('submit', sendMessage);

function sendMessage(e){
    if (e.preventDefault) e.preventDefault()
    ws.send(document.getElementById('chat_text').value);
    message_form.reset();
    return false;

下面是我的routing.py

from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from channels.auth import AuthMiddlewareStack

from chat.consumers import EchoConsumer, EchoBroadcastConsumer, ChatConsumer

    application = ProtocolTypeRouter({
        "websocket": AuthMiddlewareStack(
            URLRouter([
                
                path('ws/chat/<str:username>/', EchoBroadcastConsumer()),
                
            ]))
    })

下面是截图;我打开了两个窗口,但在一个窗口上收到了消息,而且是重复的。

enter image description here

0 个答案:

没有答案