zoukankan      html  css  js  c++  java
  • websocket 以及心跳检测实现长连接

    1:再data中定义

    heartCheck: {
    timeout: 6000,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function (ws) {
    var self = this
    this.timeoutObj && clearTimeout(this.timeoutObj)
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
    this.timeoutObj = setTimeout(function () {
    // 这里发送一个心跳,后端收到后,返回一个心跳消息,
    if (ws.readyState === 3) {
    return
    }
    console.log('发送了心跳检测')
    ws.send('HeartBeat')
    self.serverTimeoutObj = setTimeout(function () {
    console.log('检测不到心跳')
    ws.close()
    }, self.timeout)
    }, this.timeout)
    }
    }
    2:
    再created中调用
    this.initWebSocket()
    initWebSocket () { // 初始化weosocket
    this.destroyWebSocket()
    try {
    console.log('连接websocket')
    const wsuri = 'ws://' + this.dataM.split('/')[2] + '?pageId=' + generateUUID()// ws地址
    this.webSocket = new WebSocket(wsuri)
    this.webSocket.onopen = (event) => {
    console.log('send:' + this.currSceneInfo.id)
    this.webSocket.send(this.currSceneInfo.id)
    this.heartCheck.start(this.webSocket) // 心跳
    }
    this.webSocket.onmessage = (event) => {
    if (event.data === 'HeartBeat') {
    console.log('收到了心跳检测')
    this.heartCheck.start(this.webSocket) // 心跳
    } else {
    const data = JSON.parse(event.data)
     
     
    }
    }
    this.webSocket.onerror = () => {
    console.log('发生异常了')
    this.reconnect() // 重连
    }
    this.webSocket.onclose = (event) => {
    console.log('断线重连')
    this.reconnect() // 重连
    }
    } catch (e) {
    console.log(e.message)
    this.reconnect()
    }
    },
    destroyWebSocket () {
    if (this.webSocket) {
    this.webSocket.onclose = (event) => {
    console.log('链接关闭')
    }
    this.webSocket.close()
    this.webSocket = null
    }
    },

     

    destroyed () {
    this.destroyWebSocket()
    },
    reconnect () {
    if (this.lockReconnect) {
    return
    }
    this.lockReconnect = true
    // 没连接上会一直重连,设置延迟避免请求过多
    this.tt && clearTimeout(this.tt)
    this.tt = setTimeout(() => {
    this.initWebSocket()
    this.lockReconnect = false
    }, 4000)
    },
     
  • 相关阅读:
    Python学习
    我的计算机网络复习笔记(第一章)
    理解DES算法
    彻底理解RSA加密算法
    扩展欧几里得算法求模的乘法逆元
    python的deque(双向)队列详解
    对于暴力枚举的一些优化方法的题解
    python中的多(liu)元(mang)交换 ,赋值
    python定义函数后跟->的意义
    直接暴力做分糖问题
  • 原文地址:https://www.cnblogs.com/binglove/p/11736768.html
Copyright © 2011-2022 走看看