在 vue 中使用 WebSocket


<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h1>{{ res }}</h1>
  </div>
</template>

<script>
export default {
  name: 'ws',
  data () {
    return {
      msg: '',
      res: {},
      lot_id: '000',   
      ws: null,
      wsurl: ''
    }
  },
  created () {
    this.initws()
  },
  mounted () {
    this.runws()
  },
  methods: {
    runws () {
      let content = 'source=client&lots=' + this.lot_id
      if (this.ws.readyState === this.ws.OPEN) {
        this.sendmessage(content)
      } else if (this.ws.readyState === this.ws.CONNECTING) {
        let that = this
        setTimeout(function () {
          that.sendmessage(content)
        }, 300)
      } else {
        this.initws()
        let that = this
        setTimeout(function () {
          that.sendmessage(content)
        }, 500)
      }
    },
    initws () {
      this.ws = new WebSocket(this.wsurl)
      this.ws.onmessage = this.getmessage
    },
    getmessage (e) {
      this.res = JSON.parse(e.data)
    },
    sendmessage (content) {
      this.ws.send(content)
    }
  }  
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM