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)
    },
     
  • 相关阅读:
    TCP/IP、Http、Socket的区别
    MQTT协议运用总结
    求递归算法时间复杂度:递归树
    大数乘法的几种算法分析及比较(2014腾讯南京笔试题)
    3.9重建二叉树(各种方案的分析比较及扩展问题的分析)
    3.10分层遍历二叉树-扩展问题
    青春何其美好,未来的日子里希望有你
    补充招银面经 19日面的,今天28日(昨晚发的offer)
    千里送人头---厦门美团一面挂
    滴滴一面挂
  • 原文地址:https://www.cnblogs.com/binglove/p/11736768.html
Copyright © 2011-2022 走看看