在vue中实现使用webscoket进行心跳检测机制

<script>
    data() {
        // 心跳--start
        heartCheck: null,
        lockReconnect: false, //避免ws重连
        ws: null,
        wsUrl: null,
        // 心跳--end
    },
    mounted() {
        _this.heartCheck = {
      timeout: 1000, //1分钟发一次心跳
      timeoutObj: null,
      serverTimeoutObj: null,
      reset: function () {
        clearTimeout(this.timeoutObj)
        clearTimeout(this.serverTimeoutObj)
        return this
      },
      start: function () {
        var self = this
        this.timeoutObj = setTimeout(() => {
          //这里发送一个心跳,后端收到后,返回一个心跳消息,
          //onmessage拿到返回的心跳就说明连接正常
          _this.ws.send('ping')
          // console.log("ping")
          self.serverTimeoutObj = setTimeout(() => {
            //如果超过一定时间还没重置,说明后端主动断开了
            _this.ws.close() //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
          }, self.timeout)
        }, this.timeout)
      },
    }
    if (!window.WebSocket) {
      window.WebSocket = window.MozWebSocket
    }
    if (window.WebSocket) {
      _this.wsUrl = 'ws://192.168.3.54:6002/ws?projectSonId=' + localStorage.getItem('edrId')
      _this.ws = new WebSocket(_this.wsUrl) //接口地址
      _this.createWebSocket(_this.ws, _this.wsUrl)
    } else {
      alert('您的浏览器不支持WebSocket协议!')
    }
    },
    methods:{
        // 创建ws
    createWebSocket(ws, url) {
      try {
        this.initEventHandle(ws, url)
      } catch (e) {
        if (!window.WebSocket) {
          window.WebSocket = window.MozWebSocket
        }
        if (window.WebSocket) {
          _this.wsUrl = 'ws://122.14.196.211:8899/ws?projectSonId=' + localStorage.getItem('edrId')
          _this.ws = new WebSocket(_this.wsUrl) //接口地址
          _this.createWebSocket(_this.ws, _this.wsUrl)
        } else {
          alert('您的浏览器不支持WebSocket协议!')
        }
      }
    },
    // 监听
    initEventHandle(ws, wsUrl) {
      let _this = this
      ws.onclose = function () {
        if (!window.WebSocket) {
          window.WebSocket = window.MozWebSocket
        }
        if (window.WebSocket) {
          _this.wsUrl = 'ws://122.14.196.211:8899/ws?projectSonId=' + localStorage.getItem('edrId')
          _this.ws = new WebSocket(_this.wsUrl) //接口地址
          _this.createWebSocket(_this.ws, _this.wsUrl)
        } else {
          alert('您的浏览器不支持WebSocket协议!')
        }
        console.log('llws连接关闭!' + new Date().toLocaleString())
      }
      ws.onerror = function () {
        console.log('llws连接错误!')
      }
      ws.onmessage = function (event) {
        //如果获取到消息,心跳检测重置
        _this.heartCheck.reset().start() //拿到任何消息都说明当前连接是正常的
        console.log('llws收到消息啦:' + event.data)
        // console.log(event.data)
        console.log(event.data)
      }
      ws.onopen = function () {
        _this.heartCheck.reset().start() //心跳检测重置
        console.log('llws连接成功!')
      }
    },
    }
<script/>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue实现WebSocket心跳机制可以通过以下步骤进行: 1. 首先,安装WebSocket库。可以使用npm或yarn来安装,例如:`npm install vue-native-websocket`。 2. 在Vue组件引入WebSocket库,并创建WebSocket实例。可以在Vue组件的`created`或`mounted`生命周期钩子函数创建WebSocket实例。例如: ```javascript import VueNativeSock from 'vue-native-websocket'; export default { created() { Vue.use(VueNativeSock, 'ws://localhost:8080', { reconnection: true, // 是否自动重连 reconnectionAttempts: 5, // 重连尝试次数 reconnectionDelay: 3000, // 重连延迟时间(毫秒) format: 'json', // 数据格式 }); }, }; ``` 3. 添加心跳机制。可以使用Vue的定时器函数`setInterval`来定时发送心跳包。例如: ```javascript export default { created() { // 创建WebSocket实例 Vue.use(VueNativeSock, 'ws://localhost:8080', { reconnection: true, reconnectionAttempts: 5, reconnectionDelay: 3000, format: 'json', }); // 发送心跳包 setInterval(() => { this.$socket.sendObj({ type: 'heartbeat' }); }, 5000); // 每隔5秒发送一次心跳包 }, }; ``` 4. 监听心跳回复。在Vue组件监听WebSocket的消息事件,当接收到心跳回复时,可以根据需要进行相应的处理。例如: ```javascript export default { created() { // 创建WebSocket实例 Vue.use(VueNativeSock, 'ws://localhost:8080', { reconnection: true, reconnectionAttempts: 5, reconnectionDelay: 3000, format: 'json', }); // 发送心跳包 setInterval(() => { this.$socket.sendObj({ type: 'heartbeat' }); }, 5000); // 监听WebSocket消息事件 this.$socket.onMessage((message) => { const data = JSON.parse(message.data); if (data.type === 'heartbeat_reply') { // 处理心跳回复 console.log('Received heartbeat reply'); } }); }, }; ``` 这样,你就可以在Vue实现WebSocket的心跳机制了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值