vue+websocket的使用,心跳机制

一、使用步骤

代码如下(示例):

data(){
return{
      websock: null, //建立的连接
      lockReconnect: false, //是否真正建立连接
      timeout: 20 * 1000, //20秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
}
},
mounted(){
    this.iniWebSocket();

},
 methods: {
    iniWebSocket() {
      //初始化websocket
      const wsuri =
        "websocket地址";

      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    reconnect() {
      //重新连接
      var that = this;
      if (that.lockReconnect) {
        return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连,设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        //新连接
        that.iniWebSocket();
        that.lockReconnect = false;
      }, 1000);
    },
    reset() {
      //重置心跳
      var that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    },
    start() {
      //开启心跳
      var self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function () {
        //这里发送一个心跳,后端收到后,返回一个心跳消息
        if (self.websock.readyState == 1) {
          //如果连接正常
          self.websock.send("heartbeat");
        } else {
          //否则重连
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function () {
          //超时关闭
          self.websock.close();
        }, self.timeout);
      }, self.timeout);
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      let actions = { test: "12345" };
      this.websocketsend(JSON.stringify(actions));
      console.log("连接");
      //开启心跳
      this.start();
    },
    websocketonerror() {
      //连接建立失败重连
      this.iniWebSocket();
      this.reconnect();
      console.log("重新连接");
    },
    websocketonmessage(e) {
      //数据接收
      const redata = JSON.parse(e.data);
      // console.log("数据接收", redata);
      this.reset();
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      //重连
      this.reconnect();
    },
}


总结

完成

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我理解你的问题是关于在 Vue 3 和 Vite 环境下封装 WebSocket心跳机制的方法。下面是一个示例代码,供你参考: ```javascript import { ref, onMounted, onUnmounted } from 'vue' export default function useWebSocket(url) { const message = ref('') let socket = null const connectWebSocket = () => { socket = new WebSocket(url) socket.onopen = () => { console.log('WebSocket connected') socket.send('Hello, WebSocket') } socket.onmessage = event => { message.value = event.data } socket.onclose = () => { console.log('WebSocket disconnected') setTimeout(() => { connectWebSocket() }, 5000) } } const startHeartbeat = () => { setInterval(() => { if (socket.readyState === WebSocket.OPEN) { socket.send('Heartbeat') } }, 3000) } onMounted(() => { connectWebSocket() startHeartbeat() }) onUnmounted(() => { socket.close() }) return { message } } ``` 上面的代码中,我们定义了一个名为 `useWebSocket` 的自定义 Hook,它接收一个 URL 参数,用于指定 WebSocket 服务器的地址。在 `useWebSocket` 函数内部,我们使用 `ref` 创建了一个响应式的 `message` 变量,用于存储 WebSocket 收到的消息。然后,我们声明了一个 `socket` 变量,用于存储 WebSocket 连接对象。 接着,我们定义了 `connectWebSocket` 函数,它用于创建 WebSocket 连接,并在连接打开、收到消息、连接关闭时分别执行对应的操作。当连接关闭时,我们使用 `setTimeout` 函数在 5 秒后重新连接 WebSocket。 然后,我们定义了 `startHeartbeat` 函数,它用于定时发送心跳包。在 `onMounted` 生命周期钩子中,我们调用了 `connectWebSocket` 和 `startHeartbeat` 函数。在 `onUnmounted` 生命周期钩子中,我们关闭了 WebSocket 连接。最后,我们返回 `message` 变量,以便在组件中使用使用这个自定义 Hook 的示例代码如下: ```javascript <template> <div>{{ message }}</div> </template> <script> import useWebSocket from './useWebSocket' export default { setup() { const { message } = useWebSocket('wss://example.com/ws') return { message } } } </script> ``` 在组件的 `setup` 函数中,我们调用了 `useWebSocket` 自定义 Hook,将返回的 `message` 变量绑定到模板中的 `<div>` 元素上。这样,我们就完成了在 Vue 3 和 Vite 环境下封装 WebSocket心跳机制的操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值