之前全局封装的 webSocket 在某些特定的页面中使用会直接去调用 webSocket 的 onMessage 方法 已进入页面就会调,如果退出页面移除整个监听的话全局监听就会被移除
这是修改后的 全局封装
let token = uni.getStorageSync('token')
const HEARTBEAT_INTERVAL = 1 * 1000; // 心跳间隔时间,单位为毫秒
// const url = `ws://自己的地址/ws?token=${token}&bizUserType=${1}`;
class WebSocketService {
constructor() {
this.wsTask = null;
this.lastPongTime = Date.now();
this.heartbeatTimer = null;
this.webSocketType = true
// 存储页面特定监听器
this.pageListeners = new Map();
this.initSocket();
}
initSocket() {
var that = this
token = uni.getStorageSync('token')
this.wsTask = uni.connectSocket({
url: url,
success: (res) => {
that.startHeartbeat();
},
fail: (err) => {
this.webSocketType = false
console.log(err);
}
});
// 监听 WebSocket 打开事件
this.wsTask.onOpen(function(res) {});
// 监听 WebSocket