Spaces:
Sleeping
Sleeping
File size: 1,011 Bytes
ae4ceef e4b7d6f ae4ceef e4b7d6f ae4ceef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import { useEffect, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import { useStore } from '@/store/useStore';
import { getBaseUrl } from '@/lib/api';
export const useSocket = () => {
const { user, token } = useStore();
const socketRef = useRef<Socket | null>(null);
useEffect(() => {
if (!token || !user) return;
// 初始化连接,增加鉴权
const baseUrl = getBaseUrl();
const socket = io(baseUrl || window.location.origin, {
auth: { token }
});
socketRef.current = socket;
socket.on('connect', () => {
console.log('[Socket] 已认证连接');
});
// 监听全局事件 (例如管理员广播)
if (user.role === 'admin') {
socket.on('admin:circuit_breaker_change', (data) => {
console.warn('[Socket] 熔断器状态变更:', data);
// 这里可以触发一个全局 Toast
});
}
return () => {
socket.disconnect();
};
}, [token, user]);
return socketRef.current;
};
|