之前全局封装的 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 = thistoken = uni.getStorageSync('token')this.wsTask = uni.connectSocket({url: url,success: (res) => {that.startHeartbeat();},fail: (err) => {this.webSocketType = falseconsole.log(err);}});// 监听 WebSocket 打开事件this.wsTask.onOpen(function(res) {});// 监听 WebSocket 接收到服务器消息事件this.wsTask.onMessage((res) => {this.webSocketType = trueif (res.data === 'pong') {this.lastPongTime = Date.now(); // 更新接收到 pong 的时间console.log('收到服务器的心跳响应--运营端111@@@@');} else {var obj = JSON.parse(res.data)if (obj.type == "group-message-send") {var content = JSON.parse(obj.content)}}// 调用所有页面特定监听器this.pageListeners.forEach((listener, pageId) => listener(res));});// 监听 WebSocket 关闭事件this.wsTask.onClose((res) => {console.log('WebSocket 已关闭:---@@@@@运营端', res);that.closeWebSocket()this.webSocketType = false});// 监听 WebSocket 错误事件this.wsTask.onError((err) => {that.closeWebSocket()console.error('WebSocket 错误---@@@@@运营端:', err);this.webSocketType = false});}// 添加 页面监听addPageListener(pageId, listener) {if (!this.pageListeners.has(pageId)) {this.pageListeners.set(pageId, listener);}}// 移除某些页面的监听removePageListener(pageId) {if (this.pageListeners.has(pageId)) {this.pageListeners.delete(pageId);}}closeWebSocket() {this.webSocketType = falseif (this.wsTask) {this.wsTask.close({success: () => {console.log('WebSocket closed successfully');}});}}// 发送消息sendSocketMessage(msg) {this.wsTask.send({data: JSON.stringify(msg),success: () => {this.webSocketType = trueconsole.log('消息发送成功111---@@@@@运营端');// uni.$off('message')},fail: (err) => {this.webSocketType = falseconsole.error('消息发送失败:---@@@@@运营端', err);}});}// 发送心跳连接startHeartbeat() {if (this.heartbeatTimer) {clearInterval(this.heartbeatTimer); // 清除之前的定时器}this.lastPongTime = Date.now(); // 记录上一次接收到 pong 的时间this.heartbeatTimer = setInterval(() => {this.sendHeartbeat();}, HEARTBEAT_INTERVAL);}reconnect() {this.wsTask.close();this.webSocketType = falsesetTimeout(() => {this.initSocket(); // 尝试重新初始化连接}, 500); // 等待5秒后重试}// 重新连接sendHeartbeat() {const currentTime = Date.now();if (currentTime - this.lastPongTime > HEARTBEAT_INTERVAL * 2) {console.warn('心跳超时,重新连接...---@@@@@运营端');this.reconnect();return;}this.wsTask.send({data: 'ping', // 发送 ping 消息success: () => {this.webSocketType = trueconsole.log('心跳消息发送成功---@@@@@运营端');},fail: err => {this.webSocketType = falseconsole.error('心跳消息发送失败---@@@@@运营端:', err);}});}
}// 创建一个全局的 WebSocketService 实例
const webSocketService = new WebSocketService();export default webSocketService;
在页面中使用
data
pageId: Symbol('jiaohPageId'), // 创建唯一标识符
pageListener: null, // 保存页面特定监听器
onShow生命周期调用
this.onMessageChange()
在 onHide 和 onUnload 中销毁
this.$webSocketService.removePageListener(this.pageId)
this.pageListener = null;
methods 方法
onMessageChange() {this.pageListener = (res) => {console.log(res, '页面进行监听1111@@');if (res.data != 'pong' && res.data != 'ping') {var obj = JSON.parse(res.data)console.log(obj.type, '=======');switch (obj.type) {case "group-message-send":var content = JSON.parse(obj.content)if (this.getUnreadNum > 99) {this.getUnreadNum = 99} else {this.getUnreadNum += 1}break;case "new-order":this.pageNo = 1this.list = []this.init()break;}}};this.$webSocketService.addPageListener(this.pageId, this.pageListener);},