前端项目中使用Websocket实时监听数据变化

在项目中用到的Websocket监听,在这里记录一下

    data(){
      return{
        telemetryWebsocketUrl:'ws://xxxxxxxxx',
        entityId:'xxxxxx',
        entityType:'xxx',
        scope:'xxxx',
        cmdId:1,
        socket:'',
        telemetryData:{},
        historyCmds: [],
        entityDataCmds: [],
        entityDataUnsubscribeCmds: [],
        alarmDataCmds: [],
        alarmDataUnsubscribeCmds: [],
        entityCountCmds: [],
        entityCountUnsubscribeCmds: [],
        attrSubCmds: [],
        tsSubCmds:[]
      }
    },

    methods: {
      init:function() {
        let url = `${this.telemetryWebsocketUrl}?token=${window.sessionStorage.getItem('token')}`
        console.log(url)
        if(typeof WebSocket === 'undefined'){
              alert('您的浏览器不支持websocket')
        }else{
            //实例化websocket
          this.socket = new WebSocket(`${this.telemetryWebsocketUrl}?token=${window.sessionStorage.getItem('token')}`)
          // 监听socket连接
          this.socket.onopen = this.open
          // 监听socket错误信息
          this.socket.onerror = this.error
          // 监听socket消息
          this.socket.onmessage = this.getMessage
        }
      },
      open: function () {
        console.log("socket连接成功")
        let subCmds = {
          attrSubCmds: [],
          tsSubCmds: [{
            entityType: this.entityType,
            entityId: this.entityId,
            scope: this.scope,
            cmdId: this.cmdId
          }],
          historyCmds: this.historyCmds,
          entityDataCmds: this.entityDataCmds,
          entityDataUnsubscribeCmds: this.entityDataUnsubscribeCmds,
          alarmDataCmds: this.alarmDataCmds,
          alarmDataUnsubscribeCmds: this.alarmDataUnsubscribeCmds,
          entityCountCmds: this.entityCountCmds,
          entityCountUnsubscribeCmds: this.entityCountUnsubscribeCmds
        }
        this.send(JSON.stringify(subCmds))
        this.cmdId = this.cmdId ++
      },
      error: function () {
        console.log("连接错误")
      },
      getMessage: function (msg) {
        console.log("getMessage" +msg.data)
        if(msg && msg.data){
          this.telemetryData = JSON.parse(msg.data).data
          let arr = []
          for (let key in this.telemetryData) {
            // 做个中间商
            let obj = {}
            // 将对象的键赋值给新对象的name属性
            obj['name'] = key
            // 将对象的值赋值给新对象的value属性
            obj['value'] = this.telemetryData[key]
            arr.push(obj)
          }
          console.log(arr);
        }

      },
      send: function (subCmds) {
          console.log('订阅命令数据===>' + subCmds)
          this.socket.send(subCmds)
      },
      close: function () {
        console.log("socket已经关闭")
      }
    },
    mounted() {
      this.init()
    },
    destroyed () {
      // 销毁监听
      this.socket.onclose = this.close
    }
  }

版权声明:本文为weixin_54931571原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。