【发布时间】:2017-12-02 19:47:12
【问题描述】:
我正在努力了解 Django 的频道包,并希望尝试在同一页面上执行不同的操作时拥有更大的灵活性。我一直试图弄清楚为什么我的 webSocketBridge 不起作用,因为它看起来应该可以查看其他示例。
这是应用路由:
channel_routing = [
route('websocket.connect', ws_connect),
route('websocket.disconnect', ws_disconnect),
route('websocket.receive', ws_receive),
]
custom_routing = [
route("chat.receive", receive_chat_message, command="^send$"),
]
settings.py 读取的主路由:
channel_routing = [
include("ChatApp.routing.channel_routing", path=r"^/chat/stream/$"),
include("ChatApp.routing.custom_routing"),
]
消费者,甚至没有被调用:
@channel_session_user
def receive_chat_message(message):
log.debug("ws recieved a message")
try:
data = json.loads(message['text'])
except ValueError:
log.debug("ws message isn't json text")
return
if 'message' not in data:
log.debug("ws message unexpected format data=%s", data)
return
if data:
room = Room.objects.first()
log.debug('chat message handle=%s message=%s', message.user, data['message'])
reply = Message.objects.create(
room=room,
handle=message.user.username,
message=data['message'],
)
Group('users').send({
'text': json.dumps({
'reply': reply.message,
'handle': reply.handle,
'timestamp': reply.formatted_timestamp
})
})
然后就是当前的JS绑定到这一切了:
$(function () {
// Correctly decide between ws:// and wss://
let ws_path = "/chat/stream/";
console.log("Connecting to " + ws_path);
let webSocketBridge = new channels.WebSocketBridge();
webSocketBridge.connect(ws_path);
webSocketBridge.listen(function(data) {
if (data.username) {
const username = encodeURI(data['username']);
const user = $('li').filter(function () {
return $(this).data('username') === username;
});
if (data['is_logged_in']) {
user.html(username + ': Online');
}
else {
user.html(username + ': Offline');
}
}
});
$("#chatform").on("submit", function(event) {
event.preventDefault();
const $message = $('#message');
const message = {
'command': 'send',
'message': $message.val()
};
console.log(message);
webSocketBridge.send(JSON.stringify(message));
$message.val('').focus();
return false;
});
// Helpful debugging
webSocketBridge.socket.onopen = function () {
console.log("Connected to chat socket");
};
webSocketBridge.socket.onclose = function () {
console.log("Disconnected from chat socket");
}
});
webSockedBridge.listen() 中的所有内容似乎都在做它应该做的事情,调用ws_connect 和ws_disconnect。但是在 #chatformsubmit 上使用命令 thingy 发生的部分似乎对我不起作用。
现在它只是调用route('websocket.receive', ws_receive) 而不是自定义路由。让它使用命令缺少什么?
【问题讨论】:
标签: django websocket django-channels