javascript - 如何解决套接字不向特定通道发送消息的问题?
问题描述
我正在尝试用频道写一个烧瓶聊天。它工作得很好,但只有在发送消息时将参数“广播”设置为 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 和警报按照我的预期显示输出。
解决方案
推荐阅读
- java - 当您不知道属性名称时如何使用 Jackson Serializer
- liquibase - Liquibase generateChangeLog 命令生成无变更集
- javascript - 如何在 Javascript 中将 ArrayBuffer 转换为 11 位值并再次返回
- go - 如何在 Go 中获取包含数据结构的结构的大小?
- angular5 - 向 Material Autocomplete 添加加载指示器
- google-cloud-kms - 使用存储在 Google Cloud KMS 中的密钥签署区块链交易
- python - 将键映射到python目录中的值
- python - AWS Lambda Policy Length Exceeded - 向 lambda 函数添加规则
- c# - 如何处理因 INotifyPropertyChanged 事件导致的内存泄漏问题?
- python - 如何在 Windows 10 PC 上使用 Python 3.7 和 Mutagen 写入 ID3 标签 WFED URL 框架