0
我正在理解Django的頻道包,並希望嘗試和更靈活,當涉及到可以在同一頁上做不同的事情。我被困在試圖找出爲什麼我的webSocketBridge不工作,因爲它看起來應該看看其他例子。Django頻道 - 自定義路由似乎不工作
這裏是應用路由:
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綁定到這一切:
在webSockedBridge.listen()
裏面
$(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");
}
});
一切似乎做什麼它應該,調用ws_connect
和ws_disconnect
。但是在#chatform
上發生的那部分用命令提交的東西似乎不適用於我。
現在它只是調用route('websocket.receive', ws_receive)
而不是自定義路由。爲了使用該命令而缺少什麼?
它並沒有幫助。它仍然只使用默認的ws channel_routing中的默認接收路由。難道是因爲redis設置而不是代碼? –