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

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();
    }
  }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值