VUE+WebSocket实现实时推送

data() {
   return {
      id: 1,
      webSock: null,
      lockReconnect: false, //避免重复连接
   }
},
mounted() {
   // 调取websocket方法 写在mounted方法中
   this.initWebSocket()
},
methods: {
        // 发送websockwt请求
    initWebSocket() {
      let websocketUrl = 'ws://192.168.3.52:6078/bolt'
      // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
      this.webSock = new WebSocket(websocketUrl)
      this.webSock.onopen = this.webSocketOnOpen
      this.webSock.onerror = this.webSocketOnError
      this.webSock.onmessage = this.webSocketOnMessage
      this.webSock.onclose = this.webSocketClose
    },
    webSocketOnOpen() {
      console.log('WebSocket连接成功')
      //  传递参数  不需要传参就不传
      this.webSocketSend(this.id)
    },
    webSocketOnMessage(e) {
      //接收数据
      console.log('WebSocket 接受数据')
      console.log(e)
      将接收的数据转为json格式
      var jsonObj = JSON.parse(e.data)
      console.log(jsonObj)
    },
    webSocketClose(e) {
      console.log('断开连接', e)
      this.lockReconnect = false
      this.reconnect()
    },
    webSocketOnError(e) {
      console.log('报错信息', e)
    },
    webSocketSend(Data) {
      //发送数据发送
      this.webSock.send(Data)
    },
    // 断开重连操作
    reconnect() {
      if (this.lockReconnect) return
      this.lockReconnect = true
      let _this = this
      //没连接上会一直重连,设置延迟避免请求过多
      setTimeout(function () {
        _this.initWebSocket()
        _this.lockReconnect = false
        // _this.isOne = 1;
      }, 2000)
    },
}

猜你喜欢

转载自blog.csdn.net/z_jing0927/article/details/127515560