WebSocket封装成工具类,实现心跳监测、断开重连

1. 工具类代码

javascript 复制代码
import { Message } from 'element-ui';

export class WebSocketManager {
  constructor(url, reconnectInterval = 5000, onMessageCallback) {
    this.url = url;
    this.reconnectInterval = reconnectInterval; // 重连等待时间(毫秒)
    this.onMessageCallback = onMessageCallback; // 接收外部回调函数
    this.webSocket = null;
    this.reconnectAttempts = 0; // 重连尝试次数
    this.reconnectTimeout = null; // 重连定时器
    this.heartbeatInterval = null; // 心跳定时器
    this.heartbeatTimeout = 30000; // 心跳超时时间(毫秒)

    this.connect(); // 初始化连接
  }

  connect() {
    if (typeof WebSocket === 'undefined') {
      Message.warning('您的浏览器不支持 WebSocket,无法获取数据');
      return false;
    }

    this.webSocket = new WebSocket(this.url);
    this.webSocket.onopen = this.onWebSocketOpen.bind(this);
    this.webSocket.onmessage = this.onWebSocketMessage.bind(this);
    this.webSocket.onerror = this.onWebSocketError.bind(this);
    this.webSocket.onclose = this.onWebSocketClose.bind(this);
  }

  sendHeartbeat() {
    if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
      // 跟后端协商数据格式,发送心跳消息
      const obj = {
        toUserId: "-1",
        text: "[{}]"
      };
      const jsonString = JSON.stringify(obj);
      // 发送心跳消息
      this.webSocket.send(jsonString);

      // 设置心跳超时检查
      this.heartbeatTimeout = setTimeout(() => {
        if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
          this.webSocket.close(1000, '心跳超时,主动断开连接');
          this.reconnect(); // 心跳超时后尝试重连
        }
      }, this.heartbeatTimeout);
    }
  }

  onWebSocketOpen(event) {
    console.log('WebSocket 已连接:', event);
    this.reconnectAttempts = 0; // 连接成功后重连尝试次数归零

    // 启动定时发送心跳消息
   // this.heartbeatInterval = setInterval(() => this.sendHeartbeat(), 5000);
  }

  onWebSocketMessage(event) {
    console.log('收到 WebSocket 消息:', event.data);

    // 如果是心跳响应,则清除心跳超时定时器
    if (event.data === 'heartbeat') {
      clearTimeout(this.heartbeatTimeout);
    } else if (event.data === '连接成功') {
      return;
    } else {
      // 将收到的数据传递给回调函数
      if (this.onMessageCallback) {
        this.onMessageCallback(event.data);
      }
    }
  }

  onWebSocketError(event) {
    console.error('WebSocket 发生错误:', event);
  }

  onWebSocketClose(event) {
    console.log('WebSocket 已断开:', event);

    // 清理心跳相关的定时器
    clearInterval(this.heartbeatInterval);
    clearTimeout(this.heartbeatTimeout);

    // 如果重连尝试次数超过限制,则不再尝试重连
    if (this.reconnectAttempts >= 20) {
      console.error(`超过重连尝试次数限制20次,放弃重连。`);
    } else {
      this.reconnect(); // 尝试重连
    }
  }

  reconnect() {
    this.reconnectAttempts++; // 重连尝试次数加一
    console.log(`正在进行第 ${this.reconnectAttempts} 次重连尝试`);
    this.webSocket = null; // 断开现有连接
    this.heartbeatTimeout = null; // 清理心跳超时定时器
    this.heartbeatInterval = null; // 清理心跳定时器

    // 等待一段时间后重新连接
    this.reconnectTimeout = setTimeout(() => {
      this.connect();
    }, this.reconnectInterval);
  }

  sendWebSocketMessage(message) {
    if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
      this.webSocket.send(message);
    }
  }

  close() {
    if (this.webSocket) {
      this.webSocket.close(); // 关闭 WebSocket 连接
    }
    clearInterval(this.heartbeatInterval); // 清理心跳定时器
    clearTimeout(this.reconnectTimeout); // 清理重连定时器
    clearTimeout(this.heartbeatTimeout); // 清理心跳超时定时器
  }
}

2. 使用

javascript 复制代码
import { WebSocketManager } from '@/utils/websocket.js'
export default {
  data() {
    return {
      list: [],
      webSocketManager: null // 实时巡检websocket
    }
  },
   mounted() {
  	this.setRealTimeRouteInspection()
  },
  beforeDestroy() {
    // 组件销毁时关闭 WebSocket 连接
    if (this.webSocketManager) {
      this.webSocketManager.close()
    }
  },
  methods: {
  	setRealTimeRouteInspection() {
      if (!this.list.length) return
      const newOnFlyList = this.list.filter((item) => item.xjstatus == '1') // 筛选出执行中的工单
      const ids = newOnFlyList.map((item) => item.tid)
      // 获取实时巡检路线
      // window.DSE.realTrajectoryServerPath换成你自己的ip地址,ids[0]换成你自己的参数
      this.webSocketManager = new WebSocketManager(
        `${window.DSE.realTrajectoryServerPath}/zhxj/api/pushMessage/${ids[0]}`,
        5000,
        this.handleWebSocketMessage
      )
    },
    // 获取并处理websocket数据
    handleWebSocketMessage(rawData) {
      try {
        // 解析数据,需要换成你们自己后端定义的数据格式
        const data = JSON.parse(rawData)
        const tackList = JSON.parse(data.text)
        if (!tackList.length) {
          console.log('暂无实时巡检轨迹')
          return
        }
        const realTimeTracklist = tackList.map((el) => [
          Number(el.lgtd),
          Number(el.lttd)
        ])

        console.log('🚀实时巡检轨迹数据:', realTimeTracklist)
       
      } catch (error) {
        throw new Error(error)
      }
    },
  }
相关推荐
Godspeed Zhao2 小时前
现代智能汽车中的无线技术106——ETC(0)
网络·人工智能·汽车
枷锁—sha3 小时前
【pwn系列】Pwndbg 汇编调试实操教程
网络·汇编·笔记·安全·网络安全
盟接之桥4 小时前
盟接之桥EDI软件:API数据采集模块深度解析,打造企业数据协同新引擎
java·运维·服务器·网络·数据库·人工智能·制造
2501_907136824 小时前
离线工具箱 内含53个小工具
linux·服务器·网络
时空潮汐5 小时前
神卓N600 NAS身份核验功能深度解析
linux·运维·网络·神卓nas·神卓n600 pro·家庭轻nas
rfidunion5 小时前
springboot+VUE+部署(12。Nginx和前端配置遇到的问题)
前端·vue.js·spring boot
一路往蓝-Anbo5 小时前
第 7 章:内存地图 (Memory Map) 深度设计——DDR 与 SRAM
linux·stm32·单片机·嵌入式硬件·网络协议
vx-Biye_Design5 小时前
servlet家政公司管理系统-计算机毕业设计源码01438
java·vue.js·spring·servlet·tomcat·maven·mybatis
FYKJ_20105 小时前
springboot大学校园论坛管理系统--附源码42669
java·javascript·spring boot·python·spark·django·php
一路往蓝-Anbo6 小时前
第 8 章:M33 领航——引导 A35 加载 U-Boot 与 Linux 内核
linux·运维·服务器·stm32·单片机·嵌入式硬件·网络协议