vue + websocket

websocket.js

import { store } from '../store'
/** 长链接,用于接收推送 */
class WsKeepAlive {
  _isConnected =false
  /**
   *长链接,用于接收推送
   */
  constructor (sendData) {
    this.ws = new WebSocket('ws://192.168.17.69:8080/websocket/' + sendData.deviceCode) //建立连接时的传值
    const that = this
    this.ws.onopen = function open () {
      console.log('WsKeepAlive opened')
      that._isConnected = true
    }
    this.ws.onmessage = this.onMessage
    this.ws.onerror = this.onError
    this.ws.onclose = this.onClose.bind(this)
  }
  /**
   * 是否连接成功
   * @returns
   */
  isConnected () {
    return this._isConnected
  }
  /**
   * webSocket数据接收通知
   * @param {*} event
   */
  onMessage (event) {
    console.log('onMessage:' + event.data)
    store.state.websocketData = event.data // 此处为websocket推送数据,存到vuex websocketData中
  }
  /**
   * 断开webSocket链接
   *
   */
  closeWebsocket () {
    this.ws.close()
  }
  /**
   * 关闭事件通知
   * @param {*} error
   */
  onError (error) {
    console.log('WsKeepAlive error:' + error)
  }
  /**
   * 关闭事件通知
   * @param {*} error
   */
  onClose (error) {
    console.log('WsKeepAlive closed:' + error)
  }
  /**
   * 发送协议请求数据
   * @param {*} msg
   */
  //getPushData (msg) {
  //  const that = this
  //  return new Promise((resolve, reject) => {
  //    this.ws.send(msg)
  //    this.ws.onmessage = function name (event) {
  //      console.log('getPushData revData:' + event.data)
  //      resolve(event.data)
  //      that.ws.onmessage = that.onMessages
  //    }
  //  })
  //}
}
export {WsKeepAlive}

使用:

<script>
import { WsKeepAlive } from '@/utils/websocket'
export default {
  name: 'Monitor',
  data () {
    return {
      getWS: null,
      closeFlag: true,
      pushData: []
    }
  },
  computed: {
    websocketData () {
      return this.$store.state.websocketData //vuex websocket数据
    }
  },
  watch: {
    // 监听关闭值,断开websocket链接(需要断开时调用:this.getWS.closeWebsocket())
    closeFlag (val) {
      if (!val) {
        this.getWS.closeWebsocket()
      }
    },
    // 监听websocket推送数据
    websocketData (val) {
      if (val !== '连接成功!') { //第一次推送回的数据可能是'连接成功!'
        this.pushData = JSON.parse(val) //处理推送数据
      }
    }
    mounted(){
      // 建立websocket连接
      let sendData = {deviceCode: deviceCode}
      this.getWS = new WsKeepAlive(sendData)
	}
  }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值