diff --git a/im-uniapp/App.vue b/im-uniapp/App.vue index 72cb7d5..06664b8 100644 --- a/im-uniapp/App.vue +++ b/im-uniapp/App.vue @@ -49,16 +49,11 @@ } }); wsApi.onClose((res) => { - console.log("ws断开",res); - // 1000是客户端正常主动关闭 - if (res.code != 1000) { + console.log("ws断开", res); + // 3099是客户端正常主动关闭 + if (res.code != 3099) { // 重新连接 - uni.showToast({ - title: '连接已断开,尝试重新连接...', - icon: 'none', - }) - let loginInfo = uni.getStorageSync("loginInfo") - wsApi.reconnect(UNI_APP.WS_URL, loginInfo.accessToken); + this.reconnectWs(); } }) }, @@ -96,7 +91,9 @@ } // 消息回执处理,改消息状态为已读 if (msg.type == enums.MESSAGE_TYPE.RECEIPT) { - store.commit("readedMessage", { friendId: msg.sendId }) + store.commit("readedMessage", { + friendId: msg.sendId + }) return; } // 标记这条消息是不是自己发的 @@ -280,6 +277,27 @@ return true; } return loginInfo.expireTime < new Date().getTime(); + }, + reconnectWs() { + // 重新加载一次个人信息,主要是防止断线太久导致token已经过期 + this.reloadUserInfo().then((userInfo) => { + store.commit("setUserInfo", userInfo); + // 重新连接 + uni.showToast({ + title: '连接已断开,尝试重新连接...', + icon: 'none', + }) + let loginInfo = uni.getStorageSync("loginInfo") + wsApi.reconnect(UNI_APP.WS_URL, loginInfo.accessToken); + }).catch(() => { + this.exit(); + }) + }, + reloadUserInfo() { + return http({ + url: '/user/self', + method: 'GET' + }) } }, onLaunch() { diff --git a/im-uniapp/common/wssocket.js b/im-uniapp/common/wssocket.js index 7c6acff..d7cce1a 100644 --- a/im-uniapp/common/wssocket.js +++ b/im-uniapp/common/wssocket.js @@ -6,6 +6,7 @@ let connectCallBack = null; let isConnect = false; //连接标识 避免重复连接 let rec = null; let isInit = false; +let lastConnectTime = new Date(); // 最后一次连接时间 let init = () => { // 防止重复初始化 @@ -64,6 +65,7 @@ let connect = (url, token) => { if (isConnect) { return; } + lastConnectTime = new Date(); uni.connectSocket({ url: wsurl, success: (res) => { @@ -86,10 +88,13 @@ let reconnect = (wsurl, accessToken) => { //如果已经连上就不在重连了 return; } + // 延迟10秒重连 避免过多次过频繁请求重连 + let timeDiff = new Date().getTime() - lastConnectTime.getTime() + let delay = timeDiff < 10000 ? 10000 - timeDiff : 0; rec && clearTimeout(rec); - rec = setTimeout(function() { // 延迟15秒重连 避免过多次过频繁请求重连 + rec = setTimeout(function() { connect(wsurl, accessToken); - }, 15000); + }, delay); }; //设置关闭连接 diff --git a/im-uniapp/store/chatStore.js b/im-uniapp/store/chatStore.js index a89fae7..f889660 100644 --- a/im-uniapp/store/chatStore.js +++ b/im-uniapp/store/chatStore.js @@ -294,6 +294,8 @@ export default { }); // 将消息一次性装载回来 state.chats = cacheChats; + // 断线重连后不能使用缓存模式,否则会导致聊天窗口的消息不刷新 + cacheChats = state.chats; this.commit("saveToStorage"); }, saveToStorage(state) {