Browse Source

fix: ws断线重连失败的bug

master
xsx 2 years ago
parent
commit
1cb3fed3cd
  1. 38
      im-uniapp/App.vue
  2. 9
      im-uniapp/common/wssocket.js
  3. 2
      im-uniapp/store/chatStore.js

38
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() {

9
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);
};
//设置关闭连接

2
im-uniapp/store/chatStore.js

@ -294,6 +294,8 @@ export default {
});
// 将消息一次性装载回来
state.chats = cacheChats;
// 断线重连后不能使用缓存模式,否则会导致聊天窗口的消息不刷新
cacheChats = state.chats;
this.commit("saveToStorage");
},
saveToStorage(state) {

Loading…
Cancel
Save