vue实现一个websocket

引入socket io

import io from 'socket.io-client'

实现一个socket并获取到数据

try {
        const socket = io(`${SOKET_URL}/monitor`)
        this.socket = socket
        console.log('初始化socket', socket)
        this.socket.open()
        this.socket.on('real_data', ({data}) => {
          console.log('data', data)
          const res = JSON.parse(data)

          // this.res = res
          // console.log('res', JSON.stringify(res))
          const { deviceNumber, deviceType } = res
          // if (deviceNumber === 'M0000000001') return
          // if (fd=== res.fd) {
          const gfh= this.gfh
          if (deviceType === 0) {
            // 轿顶设备
            gfh.floorNum = res.floorNum
            gfh.direction =
                res.direction === 0
                  ? '停止'
                  : res.direction === 1
                    ? '上行'
                    : '下行'
            // monitorData.voltage1 = randomNumber(3.5, 4.2)
            gfh.actualDistance = res.actualDistance + 'm'
            gfh.leftDoor = res.leftDoor === 0 ? '开启' : '关闭'
            gfh.rightDoor = res.rightDoor === 0 ? '开启' : '关闭'
            gfh.actualSpeed = res.speed
            gfh.carvoltageStatus =
                res.voltageStatus === 0 ? '正常' : '异常'
            gfh.carvoltage =
                res.actualVoltage + 'V'
            gfh.radarStatus = res.radarStatus === 0 ? '正常' : '异常'
            gfh.trappedPeople = res.trappedPeople === 0 ? '否' : '是'
          } else {
            // 机房设备
            // monitorData.wire = res.wire
            gfh.temperature = res.actualTemp + '°C'
            gfh.roomvoltageStatus =
                res.voltageStatus === 0 ? '正常' : '异常'
            gfh.roomvoltage =
                res.actualVoltage + 'V'
            //  monitorData.actualTemp = res.tempStatus + '°C'
            gfh.actualWire =
                res.actualWire.length > 0 ? res.actualWire : '0,0,0,0'
            gfh.tempStatus = res.tempStatus === 0 ? '正常' : '异常'
          }
          this.gfh= gfh
          console.log(this.monitorData)
          // }
        })
      } catch (e) {
        console.log(e)
      }

注意需要后端配合
否则可以使用ajax长轮询的方式来实现
页面销毁关闭socket

beforeDestroy () {
    clearInterval(this.timer)
    this.socket && this.socket.close()
    //this.source && this.source.close()
  },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值