Spaces:
Sleeping
Sleeping
| 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; | |
| }; | |