聊天问题修复优化

This commit is contained in:
2025-12-05 19:19:44 +08:00
parent 9e275b0faf
commit a65b0e83b1
7 changed files with 438 additions and 162 deletions

View File

@@ -16,10 +16,13 @@ export const useChatStore = defineStore("chat", {
socketTask: null,
onReceiveMsg: () => {},
chatList: [],
shop_id: uni.getStorageSync("shopId"),
token: uni.getStorageSync("iToken").tokenValue || "",
group_id:'',
isManualClose: false, // 是否主动关闭true不重连false自动重连
heartbeatTimer: null, // 心跳定时器
reconnectTimer: null, // 重连定时器
connectionMonitorTimer: null, // 连接状态监控定时器
reconnectCount: 0, // 当前重连次数
maxReconnectCount: 5, // 最大重连次数(避免无限重连)
reconnectDelay: 1000, // 初始重连延迟ms
@@ -28,6 +31,7 @@ export const useChatStore = defineStore("chat", {
isAppActive: true, // 应用是否在前台
lastHeartbeatTime: 0, // 上次心跳时间戳
lastConnectTime: 0, // 上次连接时间(防止短时间内频繁连接)
// ========== 新增:修复未定义的状态 ==========
_listenersInitialized: false, // 状态监听器是否已初始化
@@ -39,6 +43,9 @@ export const useChatStore = defineStore("chat", {
recentMessages: new Map(), // 最近处理的消息映射表key=消息特征哈希value=处理时间戳
deduplicationWindow: 5000, // 去重时间窗口5秒内相同消息只处理一次
maxRecentMessages: 100, // 最近消息缓存最大数量
// ========== 新增:多页面消息监听支持 ==========
receiveMsgCallbacks: [], // 消息接收回调队列,支持多页面同时监听
};
},
@@ -91,6 +98,7 @@ export const useChatStore = defineStore("chat", {
// 2. 重置重连状态
this.reconnectCount = 0;
this.stopHeartbeat();
this.stopConnectionMonitor();
// 3. 立即重新连接
setTimeout(() => {
@@ -128,13 +136,14 @@ export const useChatStore = defineStore("chat", {
{
type: "OnbocChat",
operate_type: "init",
shop_id: uni.getStorageSync("shopId"),
token: uni.getStorageSync("iToken").tokenValue || "",
shop_id: this.shop_id,
token: this.token,
},
false
);
},
// ========== 增强发送消息容错性 ==========
sendMessage(msg, isAutoAppend = true) {
// 1. 主动关闭状态:提示用户
if (this.isManualClose) {
@@ -144,13 +153,14 @@ export const useChatStore = defineStore("chat", {
});
}
// 2. 连接未建立:尝试重连后发送
if (!this.isConnect) {
// 2. 连接未建立或SocketTask失效:尝试重连后发送
if (!this.isConnect || !this.socketTask) {
console.warn("Socket连接未建立尝试重连...");
this.reconnect();
// 延迟发送,确保重连成
// 延长延迟时间,确保重连
setTimeout(() => {
this.sendMessage(msg, isAutoAppend);
}, this.reconnectDelay);
}, 1500);
return;
}
@@ -166,25 +176,41 @@ export const useChatStore = defineStore("chat", {
}
: msg;
this.socketTask.send({
data: JSON.stringify(message),
success: (res) => {
console.log("发送成功", res);
},
fail: (error) => {
console.log("发送失败", error);
// 发送失败可能是连接断开,触发重连
if (!this.isManualClose) {
this.reconnect();
}
},
});
try {
this.socketTask.send({
data: JSON.stringify(message),
success: (res) => {
console.log("发送成功", res);
},
fail: (error) => {
console.error("发送失败,触发重连", error);
// 发送失败可能是连接断开,触发重连
if (!this.isManualClose) {
this.forceReconnect();
// 重连后重试发送
setTimeout(() => {
this.sendMessage(msg, isAutoAppend);
}, 1500);
}
},
});
} catch (error) {
console.error("发送消息异常,触发重连", error);
// 捕获异常,立即重连
if (!this.isManualClose) {
this.forceReconnect();
// 重连后重试发送
setTimeout(() => {
this.sendMessage(msg, isAutoAppend);
}, 1500);
}
}
},
// ========== 发送心跳包 ==========
sendHeartbeat() {
// 应用在后台时可调整心跳策略(如降低频率)
if (!this.isConnect || this.isManualClose) return;
if (!this.isConnect || this.isManualClose || !this.socketTask) return;
const now = Date.now();
// 记录心跳时间
@@ -196,7 +222,7 @@ export const useChatStore = defineStore("chat", {
}),
fail: (error) => {
console.log("心跳发送失败,触发重连", error);
this.reconnect();
this.forceReconnect();
},
});
},
@@ -224,6 +250,31 @@ export const useChatStore = defineStore("chat", {
this.heartbeatTimer = null;
}
},
// ========== 新增:启动连接状态监控 ==========
startConnectionMonitor() {
// 清除旧定时器
if (this.connectionMonitorTimer) {
clearInterval(this.connectionMonitorTimer);
}
// 每30秒检查一次连接状态
this.connectionMonitorTimer = setInterval(() => {
// 如果应该连接但实际未连接,触发重连
if (!this.isManualClose && this.isConnect && !this.socketTask) {
console.warn("连接监控:发现连接状态异常,强制重置");
this.forceReconnect();
}
}, 30000);
},
// ========== 新增:停止连接状态监控 ==========
stopConnectionMonitor() {
if (this.connectionMonitorTimer) {
clearInterval(this.connectionMonitorTimer);
this.connectionMonitorTimer = null;
}
},
// ========== 智能重连逻辑 ==========
reconnect() {
@@ -235,19 +286,26 @@ export const useChatStore = defineStore("chat", {
console.log("正在建立连接中,跳过重连");
return;
}
// 3. 短时间内已尝试连接:不重连(防止频繁连接)
const now = Date.now();
if (now - this.lastConnectTime < 1000) {
console.log("短时间内已尝试连接,跳过重连");
return;
}
// 3. 超过最大重连次数:停止重连
// 4. 超过最大重连次数:停止重连
if (this.reconnectCount >= this.maxReconnectCount) {
console.log("已达最大重连次数,停止重连");
return;
}
// 4. 清除旧重连定时器
// 5. 清除旧重连定时器
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
}
// 5. 计算重连延迟退避算法1s → 2s → 4s → 8s → 8s...
// 6. 计算重连延迟退避算法1s → 2s → 4s → 8s → 8s...
const delay = Math.min(
this.reconnectDelay * Math.pow(2, this.reconnectCount),
this.maxReconnectDelay
@@ -255,7 +313,7 @@ export const useChatStore = defineStore("chat", {
console.log(`${this.reconnectCount + 1}次重连,延迟${delay}ms`);
// 6. 延迟执行重连
// 7. 延迟执行重连
this.reconnectTimer = setTimeout(() => {
this.connectSocket();
this.reconnectCount++;
@@ -271,11 +329,18 @@ export const useChatStore = defineStore("chat", {
isConnecting: this.isConnecting,
isManualClose: this.isManualClose
});
// 关键:如果 socketTask 已失效但 isConnect 为 true强制重置状态
if (this.isConnect && !this.socketTask) {
console.warn("Socket连接状态异常强制重置");
this.isConnect = false;
this.forceReconnect();
}
return;
}
// 2. 设置连接中状态
this.isConnecting = true;
this.lastConnectTime = Date.now();
// 3. 重置主动关闭标记
this.isManualClose = false;
@@ -309,6 +374,7 @@ export const useChatStore = defineStore("chat", {
// 缩短心跳间隔到15s更频繁的心跳维持连接活跃
this.heartbeatInterval = 15000;
this.startHeartbeat();
this.startConnectionMonitor(); // 启动连接状态监控
// 初始化状态监听(仅在首次连接时执行)
if (!this._listenersInitialized) {
@@ -357,7 +423,7 @@ export const useChatStore = defineStore("chat", {
this.isConnect = false;
this.isConnecting = false;
// 错误触发重连
this.reconnect();
this.forceReconnect();
});
// 8. 连接关闭回调(区分主动/意外关闭)
@@ -367,6 +433,7 @@ export const useChatStore = defineStore("chat", {
this.isConnect = false;
this.isConnecting = false;
this.stopHeartbeat(); // 停止心跳
this.stopConnectionMonitor(); // 停止连接状态监控
// 只有非主动关闭时才重连
if (!this.isManualClose) {
@@ -410,8 +477,41 @@ export const useChatStore = defineStore("chat", {
}
// 5. 正常处理消息
this.chatList.unshift(msg);
this.onReceiveMsg(msg);
if(this.group_id==msg.to_id){
this.chatList.unshift(msg);
}
// 触发所有消息回调(支持多页面同时监听)
this.triggerReceiveMsgCallbacks(msg);
},
// ========== 新增:触发消息回调 ==========
triggerReceiveMsgCallbacks(msg) {
// 调用旧的单个回调(兼容原有代码)
if (typeof this.onReceiveMsg === 'function') {
this.onReceiveMsg(msg);
}
// 调用所有注册的回调
this.receiveMsgCallbacks.forEach(callback => {
if (typeof callback === 'function') {
callback(msg);
}
});
},
// ========== 新增:注册消息回调 ==========
registerReceiveMsgCallback(callback) {
if (typeof callback === 'function' && !this.receiveMsgCallbacks.includes(callback)) {
this.receiveMsgCallbacks.push(callback);
}
},
// ========== 新增:移除消息回调 ==========
removeReceiveMsgCallback(callback) {
const index = this.receiveMsgCallbacks.indexOf(callback);
if (index > -1) {
this.receiveMsgCallbacks.splice(index, 1);
}
},
// ========== 新增:生成消息特征哈希 ==========
@@ -468,6 +568,7 @@ export const useChatStore = defineStore("chat", {
// 2. 停止所有定时器,清理资源
this.stopHeartbeat();
this.stopConnectionMonitor();
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;