实现 websocket 带心跳重连

本文介绍了如何在JavaScript中使用WebSocket进行实时通信,包括创建WebSocket连接、初始化处理、心跳检测和重连机制。通过实例展示了如何在实际项目中调用和维护WebSocket连接,确保前端应用与后端的高效交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import { getWebsocketUrl } from '@/api/ajax'
export default function (callback) {
  const path = getWebsocketUrl();
  const jspCode = 100;
  let websocket;
  // 避免重复连接
  let lockReconnect = false, tt;
  // 调用
  createWebSocket();

  /**
   * websocket启动
   */
  function createWebSocket() {
      try {
          if ('WebSocket' in window) {
              websocket = new WebSocket((path + "/" + jspCode).replace("http", "ws").replace("https", "ws"));
          } else {
              alert('当前浏览器 Not support websocket!')
          }
          init();
      } catch (e) {
          console.log('建立连接失败,尝试重连!' + e);
          reconnect();
      }
  }


  // 初始化连接
  function init() {
      // 连接成功建立的回调方法
      websocket.onopen = function (event) {
          console.log("WebSocket:已连接");
          // 心跳检测重置
          heartCheck.reset().start();
      };

      // 接收到消息的回调方法
      websocket.onmessage = function (event) {
          callback(event)
          heartCheck.reset().start();
      };

      // 连接发生错误的回调方法
      websocket.onerror = function (event) {
          console.log("WebSocket:发生错误");
          reconnect();
      };

      // 连接关闭的回调方法
      websocket.onclose = function (event) {
          console.log("WebSocket:已关闭");
          heartCheck.reset();// 心跳检测
          reconnect();
      };

      // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
      window.onbeforeunload = function () {
          closeWebSocket();
      };

      // 关闭连接
      function closeWebSocket() {
          websocket.close();
      }

      // 发送消息
      function send(message) {
          websocket.send('{"msg":"' + message + '"}');
      }
  }

  /**
   * websocket重连
   */
  function reconnect() {
      if (lockReconnect) {
          return;
      }
      lockReconnect = true;
      tt && clearTimeout(tt);
      tt = setTimeout(function () {
          console.log('重连中...');
          lockReconnect = false;
          createWebSocket();
      }, 4000);
  }

  /**
   * websocket心跳检测
   */
  let heartCheck = {
      timeout: 5000,
      timeoutObj: null,
      serverTimeoutObj: null,
      reset: function () {
          clearTimeout(this.timeoutObj);
          clearTimeout(this.serverTimeoutObj);
          return this;
      },
      start: function () {
          let self = this;
          this.timeoutObj && clearTimeout(this.timeoutObj);
          this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
          this.timeoutObj = setTimeout(function () {
              // 这里发送一个心跳,后端收到后,返回一个心跳消息,onmessage拿到返回的心跳就说明连接正常
              websocket.send("HeartBeat");
              // 如果超过一定时间还没重置,说明后端主动断开了
              self.serverTimeoutObj = setTimeout(function () {
                  console.log('关闭服务');
                  websocket.close();
              }, self.timeout)
          }, this.timeout)
      }
  };
}

使用方式

  	import websocket from '@/utils/websocket.js';
	websocket((data) => {
        console.log(data)
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值