处理发送消息重复的问题
This commit is contained in:
@@ -192,7 +192,7 @@
|
||||
let currentRoom = null;
|
||||
let rooms = [];
|
||||
let pendingUploads = [];
|
||||
const sentMsgIds = new Set(); // 已发送成功的消息 ID 集合,防止重复
|
||||
const sentMsgIds = new Set(); // 本地已处理的消息 ID,防止广播重复
|
||||
|
||||
function getToken() { return localStorage.getItem('token'); }
|
||||
function saveAuth(data) {
|
||||
@@ -303,8 +303,7 @@
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.type === 'new_message') {
|
||||
const msg = data.message;
|
||||
// 去重:如果消息 ID 已在发送确认集合中,忽略广播
|
||||
if (sentMsgIds.has(msg.id)) return;
|
||||
// 发送者本人不会收到自己的广播(已由后端过滤),因此直接添加
|
||||
if (currentRoom === msg.room_id) {
|
||||
appendMessage(msg);
|
||||
}
|
||||
@@ -483,7 +482,7 @@
|
||||
body: JSON.stringify({ text: text || '', attachments: pendingUploads })
|
||||
});
|
||||
const newMsg = await res.json();
|
||||
sentMsgIds.add(newMsg.id); // 记录已发送,避免广播重复
|
||||
// 不记录 sentMsgIds,因为后端已经过滤,我们直接 append
|
||||
appendMessage(newMsg);
|
||||
input.value = '';
|
||||
pendingUploads = [];
|
||||
@@ -492,13 +491,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
// 选图后自动压缩上传,然后调用 sendMessage,确保占位
|
||||
// 选图后自动压缩上传,显示占位,然后发送
|
||||
async function handleFileSelect(event) {
|
||||
const files = event.target.files;
|
||||
if (!files.length) return;
|
||||
|
||||
const token = getToken();
|
||||
// 立即显示占位消息
|
||||
const placeholderId = 'placeholder_' + Date.now();
|
||||
const placeholderMsg = {
|
||||
id: placeholderId,
|
||||
@@ -529,11 +527,11 @@
|
||||
const data = await res.json();
|
||||
if (data.path) pendingUploads.push(data.path);
|
||||
}
|
||||
// 上传完毕,移除占位并发送正式消息
|
||||
// 移除占位
|
||||
window._messagesCache = window._messagesCache.filter(m => m.id !== placeholderId);
|
||||
sendMessage(); // 会自动带上 pendingUploads
|
||||
// 发送正式消息
|
||||
sendMessage();
|
||||
} catch(e) {
|
||||
// 失败则移除占位
|
||||
window._messagesCache = window._messagesCache.filter(m => m.id !== placeholderId);
|
||||
renderMessages(window._messagesCache);
|
||||
alert('图片发送失败,请重试');
|
||||
|
||||
Reference in New Issue
Block a user