vue 集成websocket

  • Post author:
  • Post category:vue



```html
<template>
  <div class="container">
    <input v-model="msg"
           style="width: 300px;height: 100px;text-align: center;font-size: 18px;font-family: 'Agency FB';"></input>
  </div>
</template>

<script>
  export default {
    name: 'activeMonitorMapByWebsocket',
    data() {
      return {
        websock: null,
        timer: undefined,
        msg: '',
 dataping: {
          heartbeat: '心跳'
        },
        sendform: {
          userId: '123456'
        }
      }
    },
    created() {
      if (window.WebSocket) {
        this.websock = new WebSocket('ws://127.0.0.1:8080/webSocket')
        this.initWebSocket()
      } else {
        alert('浏览器不支持websocket')
      }
    },
   destroyed() {
      clearInterval(this.timer)
      this.websock.close() //离开路由之后断开websocket连接
    },
    mounted() {
      const timer = setInterval(() => {
        // 这里调用调用需要执行的方法,1为自定义的参数,
        // 由于特殊的需求它将用来区分,定时器调用和手工调用,
        // 然后执行不同的业务逻辑
        this.websocketonopen()
      }, 1000) // 每两秒执行1次
    },
 methods: {
      //初始化weosocket
      initWebSocket() {
        console.log(this.websock)
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      },
   //连接建立之后执行send方法发送数据
      websocketonopen() {
        let actions = this.sendform
        this.websocketsend(JSON.stringify(actions))
        this.sendPing()
      },
      sendPing() {
        this.timer = setInterval(() => {
          let actions = this.dataping
          this.websock.send(JSON.stringify(actions))
        }, 5000)
      },
           websocketonerror() {//连接建立失败重连
        this.initWebSocket()
      },
      websocketonmessage(e) { //数据接收
        if (e.data == '心跳连接存在' || e.data == '服务器连接成功') {
          console.log(e.data)
        } else {
          let res = JSON.parse(e.data);
          this.msg = res.msg
        }
      },
       websocketsend(Data) {//数据发送
        this.websock.send(Data)
      },
      websocketclose(e) {  //关闭
        console.log('断开连接', e)
      }
    }
  }
</script>

<style scoped lang="scss">
  .container {
    color: #20B2AA;
    margin: 100px 100px 100px 300px;
    height: 300px;
    width: 100%;
    display: flex;
    font-size: 18px;
  }
</style>



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