95 lines
3.5 KiB
JavaScript
95 lines
3.5 KiB
JavaScript
import SockJS from 'sockjs-client/dist/sockjs.min.js'; // 确保导入正确的 SockJS 文件
|
||
import { Client } from '@stomp/stompjs';
|
||
|
||
let stompClient = null;
|
||
let subscriptions = {}; // 用于存储订阅,方便取消
|
||
|
||
const connect = (onConnectedCallback, onErrorCallback) => {
|
||
// 后端 WebSocket 端点 URL (根据实际部署情况可能需要修改)
|
||
// 注意:如果后端运行在不同端口,需要写完整 URL,例如 'http://localhost:8080/ws'
|
||
// 如果前后端同源,可以直接用 '/ws'
|
||
const socket = new SockJS('http://localhost:8085/ws'); // 使用后端配置的端点 (修改为绝对路径)
|
||
stompClient = new Client({
|
||
webSocketFactory: () => socket,
|
||
reconnectDelay: 5000, // 自动重连延迟
|
||
heartbeatIncoming: 4000,
|
||
heartbeatOutgoing: 4000,
|
||
onConnect: (frame) => {
|
||
console.log('WebSocket Connected: ' + frame);
|
||
if (onConnectedCallback) {
|
||
onConnectedCallback(frame);
|
||
}
|
||
},
|
||
onStompError: (frame) => {
|
||
console.error('Broker reported error: ' + frame.headers['message']);
|
||
console.error('Additional details: ' + frame.body);
|
||
if (onErrorCallback) {
|
||
onErrorCallback(frame);
|
||
}
|
||
},
|
||
onWebSocketError: (error) => {
|
||
console.error('WebSocket Error: ', error);
|
||
if (onErrorCallback) {
|
||
onErrorCallback(error);
|
||
}
|
||
},
|
||
onDisconnect: () => {
|
||
console.log('WebSocket Disconnected');
|
||
// 清理所有订阅
|
||
subscriptions = {};
|
||
}
|
||
});
|
||
|
||
stompClient.activate();
|
||
};
|
||
|
||
const subscribe = (destination, callback) => {
|
||
if (stompClient && stompClient.connected) {
|
||
console.log(`Subscribing to ${destination}`);
|
||
const subscription = stompClient.subscribe(destination, (message) => {
|
||
console.log(`Message received from ${destination}:`, message.body);
|
||
if (callback) {
|
||
try {
|
||
callback(JSON.parse(message.body));
|
||
} catch (e) {
|
||
console.error("Error parsing message body:", e);
|
||
callback(message.body); // 如果解析失败,返回原始 body
|
||
}
|
||
}
|
||
});
|
||
subscriptions[destination] = subscription; // 存储订阅
|
||
return subscription;
|
||
} else {
|
||
console.error('Cannot subscribe, Stomp client not connected.');
|
||
return null;
|
||
}
|
||
};
|
||
|
||
const unsubscribe = (destination) => {
|
||
if (subscriptions[destination]) {
|
||
console.log(`Unsubscribing from ${destination}`);
|
||
subscriptions[destination].unsubscribe();
|
||
delete subscriptions[destination]; // 从存储中移除
|
||
}
|
||
};
|
||
|
||
const disconnect = () => {
|
||
if (stompClient && stompClient.connected) {
|
||
stompClient.deactivate();
|
||
console.log('WebSocket connection deactivated.');
|
||
}
|
||
// 即使未连接,也尝试清理 stompClient 实例
|
||
stompClient = null;
|
||
subscriptions = {}; // 清空订阅记录
|
||
};
|
||
|
||
// 可选:发送消息的方法 (如果需要前端主动发消息)
|
||
const sendMessage = (destination, body) => {
|
||
if (stompClient && stompClient.connected) {
|
||
stompClient.publish({ destination: destination, body: JSON.stringify(body) });
|
||
} else {
|
||
console.error('Cannot send message, Stomp client not connected.');
|
||
}
|
||
};
|
||
|
||
export { connect, subscribe, unsubscribe, disconnect, sendMessage }; |