赞
踩
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(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。