django频道设置路由

时间:2017-08-21 13:30:22

标签: django django-channels

我正在学习如何使用django-channel设置websocket连接,我在routing.py

中设置了此设置
from channels import route
from gallery import socket as sock

channel_routing = [
   # Wire up websocket channels to our consumers:
   route("websocket.connect", sock.ws_connect, path=r"^/render-status/$"),
   route("websocket.receive", sock.ws_receive, , path=r"^/render-status/$"),
]

以及以下javascript

// When we're using HTTPS, use WSS too.
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var ws_path = ws_scheme + '://' + window.location.host + '/render-status/';
console.log("Connecting to " + ws_path)
var socket = new ReconnectingWebSocket(ws_path);
socket.onmessage = function(message) {
   console.log("Got message: " + message.data);
   var data = JSON.parse(message.data);
   // if action is started, add new item to table
   if (data.action == "started") {

   }
   // if action is completed, just update the status
   else if (data.action == "completed"){

   }
};

var message = {
   action: "incomplete",
   job_name: "10",
};
socket.send(JSON.stringify(message));

尝试了,连接失败(从控制台)

colorpicker2.js:565 Connecting to ws://127.0.0.1:8000/render-status/
reconnecting-websocket.min.js:1 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
    at a.send (http://127.0.0.1:8000/static/js/reconnecting-websocket.min.js:1:2611)
    at HTMLDocument.<anonymous> (http://127.0.0.1:8000/static/js/colorpicker2.js:584:11)
    at k (http://127.0.0.1:8000/static/js/jquery.js:15:16962)
    at Object.fireWith [as resolveWith] (http://127.0.0.1:8000/static/js/jquery.js:15:17720)
    at Function.ready (http://127.0.0.1:8000/static/js/jquery.js:15:12435)
    at HTMLDocument.D (http://127.0.0.1:8000/static/js/jquery.js:15:9840)
send @ reconnecting-websocket.min.js:1
(anonymous) @ colorpicker2.js:584
k @ jquery.js:15
fireWith @ jquery.js:15
ready @ jquery.js:15
D @ jquery.js:15
reconnecting-websocket.min.js:1 WebSocket connection to 'ws://127.0.0.1:8000/render-status/' failed: Error during WebSocket handshake: Unexpected response code: 404
open @ reconnecting-websocket.min.js:1
a @ reconnecting-websocket.min.js:1
(anonymous) @ colorpicker2.js:566
k @ jquery.js:15
fireWith @ jquery.js:15
ready @ jquery.js:15
D @ jquery.js:15
22reconnecting-websocket.min.js:1 WebSocket connection to 'ws://127.0.0.1:8000/render-status/' failed: Error during WebSocket handshake: Unexpected response code: 404
open @ reconnecting-websocket.min.js:1
(anonymous) @ reconnecting-websocket.min.js:1

我还检查了文档https://channels.readthedocs.io/en/stable/routing.html,以确保这是您设置路径的方式。

1 个答案:

答案 0 :(得分:0)

您的路由是正确的,但是当套接字仍在尝试连接时,您发送的消息太快了。使用onopen回调确保仅在建立连接后才发送消息:

socket.onopen = function() {
    var message = {
        action: "incomplete",
        job_name: "10",
    };
    socket.send(JSON.stringify(message));
}