前端websocket 使用

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.完整的封装代码———待完善后更新

你可能感兴趣的:(vue.js)