1.安装stompjs、sockjs-client
npm install sockjs-client --save
npm install stompjs --save
2.建立连接
initWebSocket() { const socket = new SockJS(this.socketUrl); this.stompClient = Stomp.over(socket); this.stompClient.connect( // { 'token': this.token }, // 可带参 {}, () => { this.successCallback(); // 连接成功 }, () => { this.disconnect(); // 断开连接 } ); },
3.连接成功
// 连接成功 successCallback() { console.info("onConnected"); this.stompClient.subscribe("/topic/send/error", (val) => { this.showData = val.body; // 接收到的数据 }); },
4.断开连接
disconnect() { console.log("关闭连接"); this.reconnect(this.socketUrl); if (this.stompClient != null) { this.stompClient.disconnect(); } },
5.断开重连
reconnect(socketUrl) { console.info("in reconnect function"); const socket = new SockJS(socketUrl); this.stompClient = Stomp.over(socket); this.stompClient.connect( {}, () => { console.info("reconnected success"); // 连接成功 console.log("成功"); this.successCallback(); }, () => { // 失败 console.log("失败"); setTimeout(() => { this.reconnect(this.socketUrl); }, 5000); } ); },