首页 > 解决方案 > 如何解决套接字不向特定通道发送消息的问题?

问题描述

我正在尝试用频道写一个烧瓶聊天。它工作得很好,但只有在发送消息时将参数“广播”设置为 True。一旦我在@socketio.on('send message') 中将'broadcast=True' 更改为'room=room',它就完全停止发送消息。当我单击发送按钮时,没有任何反应,没有任何显示。谁能指出这里有什么问题?我花了很多天的时间,我会很感激各种提示。谢谢你。

服务器:

@socketio.on('join')
def on_join(room):
    print(f"joined channel is: {room}")
    username = session.get("name")
    join_room(room)
    data = {"username": username, "room": room}
    emit('join', data)


@socketio.on('send message')
def handleMessage(data):
    # get user's name and sent message
    print(f"sent data is: {data}")
    message = data["message"]
    name = data["name"]
    date = data["date"]
    room = data["room"]
    print(f"room is: {room}")
    # save data into messages dict   
    messages[room].append(message)

    emit("announce message", {"message": message, "name": name, "date": date},
    broadcast=True)

客户端(来自 channels.html,用户点击链接将他们重定向到特定的频道模板):

// set onclick funtion to dynamically created elements with jinja2
document.getElementById("all-channels").addEventListener(
    "click", 
    event => {
        if (event.target && event.target.matches("button")) {
            alert("every single button should fucking work");
            const room = event.target.innerHTML;
            alert(room);
            socket.emit('join', room);
        }
    }, 
    false
);

客户端(来自 channel.html,一个特定的通道模板,从中发送消息):

// configure 'send' button to emit 'send message' event
document.querySelector("#submit-message").onclick = (data) => {
    const message = document.querySelector("#message").value;
    const room = document.querySelector("#specific-channel").innerHTML;
    const name = localStorage.getItem("name");
    var date = new Date();
    date = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' ' + '|' + ' ' + date.getHours() + ":" + date.getMinutes();
    socket.emit(
        'send message', 
        {"message": message, "date": date, "room": room, "name": name}
    );
                        console.log(room);
};
              
                    
// when message is sent, add it to ul
socket.on(
    'announce message', 
    data => {
        const li = document.createElement('li');
        const name_test = data.name;
        li.innerHTML = `(${data.date} ${data.name}: ${data.message})`;
        document.querySelector("#messages").append(li);
        document.querySelector("#message").value = "";
        console.log(data);
   }
);

没有错误被抛出。Console.log 和警报按照我的预期显示输出。

标签: javascriptpythonflaskwebsocketflask-socketio

解决方案


推荐阅读