websocket Django Channels - connected不执行

fiei3ece  于 2023-08-05  发布在  Go
关注(0)|答案(1)|浏览(119)

我从Django频道的创建者那里复制了GitHub项目multichat的部分内容。
我对代码做了一些细微的改动,比如不使用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");
}

sdnqo3pr

sdnqo3pr1#

WebSocket路径应该在服务器端和客户端匹配。在服务器端有/chat-stream/,在客户端有/chat/stream。这些应该匹配。另外,确保不要忘记尾部的斜杠,因为django明确要求它。

相关问题