diff --git a/src/contexts/NotificationContext.js b/src/contexts/NotificationContext.js index 8d0ef580..518ec9c5 100644 --- a/src/contexts/NotificationContext.js +++ b/src/contexts/NotificationContext.js @@ -630,6 +630,24 @@ export const NotificationProvider = ({ children }) => { const { interval, maxBatch } = NOTIFICATION_CONFIG.mockPush; socket.startMockPush(interval, maxBatch); logger.info('NotificationContext', 'Mock push started', { interval, maxBatch }); + } else { + // ✅ 真实模式下,订阅事件推送 + console.log('%c[NotificationContext] 🔔 订阅事件推送...', 'color: #FF9800; font-weight: bold;'); + + if (socket.subscribeToEvents) { + socket.subscribeToEvents({ + eventType: 'all', + importance: 'all', + onSubscribed: (data) => { + console.log('%c[NotificationContext] ✅ 订阅成功!', 'color: #4CAF50; font-weight: bold;'); + console.log('[NotificationContext] 订阅确认:', data); + logger.info('NotificationContext', 'Events subscribed', data); + }, + // ⚠️ 不需要 onNewEvent 回调,因为 NotificationContext 已经通过 socket.on('new_event') 监听 + }); + } else { + console.warn('[NotificationContext] ⚠️ socket.subscribeToEvents 方法不可用'); + } } }); diff --git a/src/services/socketService.js b/src/services/socketService.js index 3a101041..e1cdbd07 100644 --- a/src/services/socketService.js +++ b/src/services/socketService.js @@ -68,8 +68,8 @@ class SocketService { console.log(`%c[socketService] ✅ WebSocket 已连接`, 'color: #4CAF50; font-weight: bold;'); console.log('[socketService] Socket ID:', this.socket.id); - // 连接成功后自动订阅所有事件房间 - this.subscribeToAllEvents(); + // ⚠️ 已移除自动订阅,让 NotificationContext 负责订阅 + // this.subscribeToAllEvents(); }); // 监听断开连接 @@ -352,13 +352,14 @@ class SocketService { }); // 监听新事件推送 + // ⚠️ 注意:不要移除其他地方注册的 new_event 监听器(如 NotificationContext) + // 多个监听器可以共存,都会被触发 if (onNewEvent) { console.log('[SocketService DEBUG] 设置 new_event 监听器'); - // 先移除之前的监听器(避免重复) - this.socket.off('new_event'); - console.log('[SocketService DEBUG] ✓ 已移除旧的 new_event 监听器'); - // 添加新的监听器 + // ⚠️ 已移除 this.socket.off('new_event'),允许多个监听器共存 + + // 添加新的监听器(与其他监听器共存) this.socket.on('new_event', (eventData) => { console.log('\n[SocketService DEBUG] ========== 收到新事件推送 =========='); console.log('[SocketService DEBUG] 事件数据:', eventData); @@ -370,7 +371,7 @@ class SocketService { console.log('[SocketService DEBUG] ✓ onNewEvent 回调已调用'); console.log('[SocketService DEBUG] ========== 新事件处理完成 ==========\n'); }); - console.log('[SocketService DEBUG] ✓ new_event 监听器已设置'); + console.log('[SocketService DEBUG] ✓ new_event 监听器已设置(与其他监听器共存)'); } console.log('[SocketService DEBUG] ========== 订阅完成 ==========\n');