Django Channels - 连接未执行

Django Channels - connected isn't executed

您好,我正在从 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"),
]

来自应用程序的路由:

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'])

这里是 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");
}

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