vue3使用webSocket增加心跳监测以及断线重连功能

sockets.js

import store from "@/store";
let websock: any = null;
let global_callback: any = null;
let wsuri: string | null;
//连接标识 避免重复连接
let isConnect = false;
//断线重连后,延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let rec: any = null;
// 心跳发送/返回的信息
const checkMsg = { hhh: "heartbeat" };
//每段时间发送一次心跳包 这里设置为20s
const timeout = 20000;
//延时发送消息对象(启动心跳新建这个对象,收到消息后重置对象)
let timeoutObj: any = null;
function createWebSocket() {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  if (websock == null || typeof websock !== WebSocket) {
    wsuri = sessionStorage.getItem("wsurl");
    initWebSocket(callback);
  }
}
function initWebSocket(callback: any) {
  global_callback = callback;
  // 初始化websocket
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  websock = new WebSocket(wsuri);
  websock.onmessage = function (e: any) {
    websocketonmessage(e);
  };
  // 连接发生错误的回调方法
  websock.onerror = function () {
    console.log("WebSocket连接发生错误");
    isConnect = false;
    //连接错误 需要重连
    reConnect();
    //createWebSocket();啊,发现这样写会创建多个连接,加延时也不行
  };
  websock.onclose = function (e: any) {
    websocketclose(e);
  };
  websock.onopen = function () {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    websocketOpen();
  };
}
// 实际调用的方法
function sendSock(agentData: any) {
  if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
    websocketsend(agentData);
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态,则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData);
    }, 1000);
  } else {
    // 若未开启 ,则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData);
    }, 1000);
  }
}
function closeSock() {
  websock.close();
}
// 数据接收
function websocketonmessage(msg: any) {
  // console.log("收到数据:"+JSON.parse(e.data));
  // console.log("收到数据:"+msg);
  // global_callback(JSON.parse(msg.data));
  //获取消息后 重置心跳
  clearTimeout(timeoutObj);
  timeoutObj = setTimeout(function () {
    if (isConnect) websock.send(checkMsg);
  }, timeout);

  // 收到信息为Blob类型时
  let result: any = null;
  // debugger
  if (msg.data instanceof Blob) {
    const reader = new FileReader();
    reader.readAsText(msg.data, "UTF-8");
    reader.onload = (e: any) => {
      console.log(e);
      if (typeof reader.result === "string") {
        result = JSON.parse(reader.result);
      }
      //console.log("websocket收到", result);
      global_callback(result);
    };
  } else {
    result = JSON.parse(msg.data);
    //console.log("websocket收到", result);
    global_callback(result);
  }
}
// 数据发送
function websocketsend(agentData: any) {
  console.log("发送数据:" + agentData);
  websock.send(agentData);
}
// 关闭
function websocketclose(e: any) {
  isConnect = false;
  //连接错误 需要重连
  reConnect();
  console.log("connection closed (" + e.code + ")");
}
function websocketOpen() {
  isConnect = true;
  timeoutObj = setTimeout(function () {
    if (isConnect) websock.send(checkMsg);
  }, timeout);
}
function reConnect() {
  console.log("尝试重新连接");
  //如果已经连上就不在重连了
  if (isConnect) {
    return;
  }
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  clearTimeout(rec);
  // 延迟5秒重连  避免过多次过频繁请求重连
  rec = setTimeout(function () {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    createWebSocket();
  }, 5000);
}
function callback(msg: any) {
  console.log("websocket的回调函数收到服务器信息:" + JSON.stringify(msg));
  store.dispatch("setActionData", msg);
}
export { sendSock, createWebSocket, closeSock };

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值