import { Client } from '@stomp/stompjs';
const nowLocation = window.location;
const host = nowLocation.host;
class WebSocketService {
static instance;
client;
constructor() {
this.client = new Client({
brokerURL: "ws://" + host + "/api/websocket", // replace with your actual WebSocket server URL
// connectHeaders: {
// login: 'user',
// passcode: 'password',
// },
debug: function (str) {
// console.log(str,'=============');
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
});
}
static getInstance() {
if (!WebSocketService.instance) {
WebSocketService.instance = new WebSocketService();
}
return WebSocketService.instance;
}
connect() {
this.client.activate();
}
disconnect() {
this.client.deactivate();
}
subscribe(destination, callback) {
this.client.onConnect = () => {
this.client.subscribe(destination, callback);
};
}
}
export default WebSocketService;
使用该类
onMounted(() => {});
const webSocketService = WebSocketService.getInstance();
webSocketService.connect();
webSocketService.subscribe("/topic/alarm/record/page/refresh", () => {
query();
notification.warning({
message: "设备报警,请及时查看",
duration: 3,
});
});