Django频道 - 连接未执行

时间:2017-08-03 13:27:44

标签: python django websocket django-channels

您好我正在从django频道的创建者那里复制github项目的一部分。

我对代码稍作修改,比如不使用jquery,重命名一些消费者等等。

运行代码时我没有任何错误,但是当我加入页面并且JS创建一个websocket时,它只是简单地说

[2017/08/03 13:13:48] WebSocket HANDSHAKING /chat/stream [127.0.0.1:37070]
[2017/08/03 13:13:48] WebSocket CONNECT /chat/stream [127.0.0.1:37070]

哪一个会认为是罚款当然...但是我的连接功能我有一个打印(“******** CONNECTED **********”),这是在控制台无处可见。它只是没有运行我告诉它的功能,当有人连接但它仍然说连接的人,它没有抛出任何错误。

这是主要的路由:

channel_routing = [
    include("crypto_chat.routing.websocket_routing", path=r"^/chat-stream/$"),
        include("crypto_chat.routing.chat_routing"),
]

从app进行路由:

websocket_routing = [
    route("websocket.connect", ws_connect),
    route("websocket.receive", ws_receive),
    route("websocket.disconnect", ws_disconnect),
]

chat_routing = [
    route("chat.receive", chat_send, command="^send$"),
    route("chat.receive", user_online, command="^online$"),

连接消费者:

@channel_session_user_from_http
def ws_connect(message):
    # only accept connection if you have any rooms to join
    print("******************CONNECT*************************''")
    message.reply_channel.send({"accept": True})
    # init rooms - add user to the groups and pk num to the session
    message.channel_session['rooms'] = []
    for room in Room.objects.get(users=message.user):
        room.websocket_group.add(message.reply_channel)
        message.channel_session['rooms'].append(room.pk)

    print(message.channel_session['rooms'])

Heres JS(注意:我正在使用项目网站上提供的JS扩展):

function send_msg(){
    var msg=document.getElementById('msg_input').value;
    console.log("sending msg" + msg);

    webSocketBridge.send({
                "command": "send",
                "room": "1",
                "message": msg
            });
}
    // logging
    var ws_path = "/chat/stream";
    console.log("connecting to " + ws_path);
    // connect
    var webSocketBridge = new channels.WebSocketBridge();
    webSocketBridge.connect(ws_path);
    // listen loop
    webSocketBridge.listen(function(data)
    {
        // read json file and act accordingly
        if(data.error){
            // post error message in chat
            console.log("Error - " + data.error);
            return;
        }
        // handle if the user comes back online
        if(data.online){
            console.log("User is online");
        }
        else if(data.offline){
            console.log("User offline");
        }
        else if(data.message){
            console.log("Got message");
        }
        else{  console.log("Unknown message type");  }
    });

    // Helpful debugging
webSocketBridge.socket.onopen = function () {
    console.log("Connected to chat socket");
};
webSocketBridge.socket.onclose = function () {
    console.log("Disconnected from chat socket");
}

1 个答案:

答案 0 :(得分:1)

Websocket路径应该在服务器端和客户端匹配。在服务器端,您有/chat-stream/,在客户端/chat/stream。这些应该匹配。另外,请确保不要忘记尾部斜杠为django explicitly requires it