Django频道:Echo示例问题

时间:2016-08-03 11:20:26

标签: javascript python django websocket django-channels

我正在关注channels documentation提供的示例代码并遇到了问题。 django服务器成功接受来自浏览器的websocket并且发送似乎有效。但是,消息的服务器端处理(ws_message)似乎没有发生,并且浏览器端没有注册回复(也没有任何警报)。

Sending seems to work, but no reply

此行为与Django channels - Echo example not working中观察到的非常相似。然而,虽然切换到扭曲的16.2.0是这种情况的解决方案,但我已经在扭曲16.2.0。

代码段如下:

consumers.py

from django.http import HttpResponse
from channels.handler import AsgiHandler

def ws_message(message):
    print("sending message ", message.content["text"])
    raise
    message.reply_channel.send({
        "text": message.content["text"]
    })

routing.py

from channels.routing import route
from channel_test.consumers import ws_message

channel_routing = [
    route("websocket.recieve", ws_message),
] 

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "channels",
    "channel_test",
    "argent_display"
]

CHANNEL_LAYERS = {
    "default":{
        "BACKEND": "asgiref.inmemory.ChannelLayer",
        "ROUTING": "argent_display.routing.channel_routing"
    }
}

然后运行django dev服务器(manage.py runserver),并通过浏览器控制台执行以下操作:

socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
    console.log('test');
    alert(e.data);
}
socket.onopen = function() {
    socket.send("hello world");
}

收到消息后,应发出警报并登录控制台。但是,都不会发生。

1 个答案:

答案 0 :(得分:0)

您应该将ws_message消费者与websocket.receive联系起来websocket.recieve