当前位置: 代码迷 >> 综合 >> 在vue项目中使用SockJS实现websocket通信
  详细解决方案

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

热度:13   发布时间:2024-02-02 09:55:53.0

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 = thisthis.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();}}
}