前端:
sockjs-client v1.0.0
stomp.js v2.3.3
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { Modal, Button, message, notification } from 'antd';
let socket;
let stompClient = null;
let origin = 'xxx';
class Dialog extends Component {
constructor(props) {
super(props);
this.state = {
id:'',
connectStatus: false,
};
}
componentDidMount() {
this.connect();
}
componentWillUnmount() {
}
connect() {
socket = new window.SockJS(`${origin}/xxx`, [], {
transports: 'websocket',
});
stompClient = window.Stomp.over(socket);
stompClient.debug = null; //禁用调试功能
stompClient.heartbeat.incoming = 10000;
stompClient.heartbeat.outgoing = 20000;
stompClient.connect({}, frame => {
this.setState({ connectStatus: true }); //设置连接状态
stompClient.send('/app/reception', { priority: 9 }, this.state.id);
stompClient.subscribe('/topic/reception/' + this.state.id, reception => {
let receptionInfo = JSON.parse(reception.body);
});
});
//断网,锁屏,都会走到onclose
socket.onclose = () => {
this.disconnect();
};
}
disconnect() {
if (stompClient !== null) {
//主动关闭连接
stompClient.disconnect();
}
this.setState({
connectStatus: false,
});
setTimeout(() => {
this.connect();
}, 1500); //1.5S后重连
}
}
}