当前位置:   article > 正文

在vue项目中使用SockJS实现websocket通信_unity vue sockjs

unity vue sockjs

1.引入SockJS 和Stomp

npm install sockjs-client

npm install stompjs

 

import SockJS from 'sockjs-client'

import Stomp from 'stompjs'

 

2.代码实现

data() {
  return {
    stompClient:  '',
    timer: ''
  }
},
mounted () {
  this.init()
},
beforeDestroy() {
  // 如果跳转别的页面的时候不仍保持websocket通信,此步可注释,否则定时器要清除
  //clearInterval(this.timer)
  this.disconnect()
},
methods: {
  init () {
    this.connection()
    let _this = this
    // 断开重连机制
    this.timer = setInterval( () => {
      try {
        _this.stompClient.send('test')
      } catch (e) {
        console.log('连接中断:' + e)
        _this.connection()
      }
    }, 10000)
  },
  connection () {
    let socket = new SockJS('/vehiclemanage/websocketServer')//后端提供协议字段
    this.stompClient = Stomp.over(socket)
    let __this = this
    this.stompClient.connect(
      {},
      function connectCallback() {
        __this.stompClient.subscribe('/personrecognize', (response) => {//后端提供订阅地址
          console.log(response)//接收后端response数据
        })
      },
      function errorCallBack(error) {
        console.log('连接失败:' + error);
      }
    )
  },
  disconnect () {
    //console.log(this.timer)
    //clearInterval(this.timer)
    if (this.stompClient) {
      this.stompClient.disconnect();
    }
  }
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/814765
推荐阅读
相关标签
  

闽ICP备14008679号