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)
    },
}

  • 5
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值