【发布时间】:2016-12-09 02:06:34
【问题描述】:
我正在关注channels documentation 提供的示例代码,但遇到了问题。 django 服务器成功地接受来自浏览器的 websocket 并且发送似乎工作。然而,消息(ws_message)的服务器端处理似乎没有发生,并且浏览器端没有注册任何回复(也没有任何警报)。
Sending seems to work, but no reply
此行为与在Django channels - Echo example not working 中观察到的行为非常相似。然而,虽然切换到 twisted 16.2.0 是这种情况的解决方案,但我已经在使用 twisted 16.2.0。
代码sn-ps如下:
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 开发服务器(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");
}
收到消息后,应发出警报并登录控制台。但是,两者都没有发生。
【问题讨论】:
标签: javascript python django websocket django-channels