我正在尝试与频道进行烧瓶聊天。它工作得很好,但是仅在发送消息时将参数“ broadcast”设置为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和警报按预期显示输出。