• 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)
    },
     
  • 相关阅读:
    经典管理定理6条
    从《乔家大院》悟企业留人
    大型Web2.0站点构建技术初探(转)
    从《投名状》谈创业如何“兄弟”共赢
    web2.0站点的考虑
    如何管理很“牛”的员工?
    五种提高 SQL 性能的方法
    破译犹太商人成功密码
    通过了解MySpace的六次重构经历,来认识分布式系统到底该如何创建
    业务员的3个经典故事
  • 原文地址:https://www.cnblogs.com/binglove/p/11736768.html
Copyright © 2020-2023  润新知