关于vue.js:前端websocket-使用

6次阅读

共计 953 个字符,预计需要花费 3 分钟才能阅读完成。

1. 结构 WebSocket 实例

var ws = new WebSocket('ws://localhost:8080');

2. 以后实例的 readyState 状态

WebSocket 的四种状态
CONNECTING:值为 0,示意正在连接。OPEN:值为 1,示意连贯胜利,能够通信了。CLOSING:值为 2,示意连贯正在敞开。CLOSED:值为 3,示意连贯曾经敞开,或者关上连贯失败。

3. 实例属性回调函数

ws.onopen = (e)=> {console.log("连贯胜利")
}
ws.onmessage= (e)=> {console.log("接管音讯胜利")
}
ws.onoerror = (e)=> {console.log("连贯失败")
}
ws.onclose = (e)=> {console.log("连贯敞开")
}

4. 重连

 // 重连
  reConnection(){console.log("从新连贯")
    if(this.lockReconnect){return}
    this.lockReconnect = true
    if(this.timerReconnect) {clearTimeout(this.timerReconnect)
    } 

    // 没连上会始终重连,设置迟延,防止申请过多
    this.timerReconnect = setTimeout(() => { //setTimeout 到点了执行
      this.createWebSocket()
      this.lockReconnect = false
    }, 5000);
    
  }

5. 监测心跳

heartCheck(){console.log("监测心跳")
    if(this.timerHeart){clearTimeout(this.timerHeart)
    }

    if(this.timerServerHeart){clearTimeout(this.timerServerHeart)
    }

    this.timerHeart = setTimeout(() => {this.ws.send("are you weak")

      this.timerServerHeart = setTimeout(() => {
        // 断了
        this.ws.close()}, 5000);

      this.lockReconnect = false
    }, 2000);

  }

6. 残缺的封装代码———待欠缺后更新

正文完
 0