feat:. mockSocketService 添加 connecting 状态

- 新增 connecting 标志防止重复连接
  - 在 connect() 方法中检查 connected 和 connecting 状态
  - 连接成功或失败后清除 connecting 标志\
2. NotificationContext 调整监听器注册顺序

  - 在 useEffect 中重新排序初始化步骤
  - 第一步:注册所有事件监听器(connect, disconnect, new_event 等)
  - 第二步:获取最大重连次数
  - 第三步:调用 socket.connect()
  - 使用空依赖数组 [] 防止 React 严格模式重复执行\
3. logger 添加日志限流

  - 实现 shouldLog() 函数,1秒内相同日志只输出一次
  - 使用 Map 缓存最近日志,带最大缓存限制(100条)
  - 应用到所有 logger 方法:info, warn, debug, api.request, api.response
  - 错误日志(error, api.error)不做限流,始终输出\
修复 emit 时机确保事件被接收

  - 在 mockSocketService 的 connect() 方法中
  - 使用 setTimeout(0) 延迟 emit(connect) 调用
  - 确保监听器注册完毕后再触发事件\
This commit is contained in:
zdl
2025-10-27 13:13:56 +08:00
parent 227e1c9d15
commit a9dc1191bf
5 changed files with 182 additions and 40 deletions

View File

@@ -303,6 +303,7 @@ const mockFinancialNews = [
class MockSocketService {
constructor() {
this.connected = false;
this.connecting = false; // 新增:正在连接标志,防止重复连接
this.listeners = new Map();
this.intervals = [];
this.messageQueue = [];
@@ -325,18 +326,30 @@ class MockSocketService {
* 连接到 mock socket
*/
connect() {
// ✅ 防止重复连接
if (this.connected) {
logger.warn('mockSocketService', 'Already connected');
console.log('%c[Mock Socket] Already connected, skipping', 'color: #FF9800; font-weight: bold;');
return;
}
if (this.connecting) {
logger.warn('mockSocketService', 'Connection in progress');
console.log('%c[Mock Socket] Connection already in progress, skipping', 'color: #FF9800; font-weight: bold;');
return;
}
this.connecting = true; // 标记为连接中
logger.info('mockSocketService', 'Connecting to mock socket service...');
console.log('%c[Mock Socket] 🔌 Connecting...', 'color: #2196F3; font-weight: bold;');
// 模拟连接延迟
setTimeout(() => {
// 检查是否应该模拟连接失败
if (this.failConnection) {
this.connecting = false; // 清除连接中标志
logger.warn('mockSocketService', 'Simulated connection failure');
console.log('%c[Mock Socket] ❌ Connection failed (simulated)', 'color: #F44336; font-weight: bold;');
// 触发连接错误事件
this.emit('connect_error', {
@@ -351,6 +364,7 @@ class MockSocketService {
// 正常连接成功
this.connected = true;
this.connecting = false; // 清除连接中标志
this.reconnectAttempts = 0;
// 清除自定义重连定时器
@@ -360,9 +374,15 @@ class MockSocketService {
}
logger.info('mockSocketService', 'Mock socket connected successfully');
console.log('%c[Mock Socket] ✅ Connected successfully!', 'color: #4CAF50; font-weight: bold; font-size: 14px;');
console.log(`%c[Mock Socket] Status: connected=${this.connected}, connecting=${this.connecting}`, 'color: #4CAF50;');
// 触发连接成功事件
this.emit('connect', { timestamp: Date.now() });
// ✅ 使用 setTimeout(0) 确保监听器已注册后再触发事件
setTimeout(() => {
console.log('%c[Mock Socket] Emitting connect event...', 'color: #9C27B0;');
this.emit('connect', { timestamp: Date.now() });
console.log('%c[Mock Socket] Connect event emitted', 'color: #9C27B0;');
}, 0);
// 在连接后3秒发送欢迎消息
setTimeout(() => {

View File

@@ -25,4 +25,73 @@ console.log(
`color: ${useMock ? '#FF9800' : '#4CAF50'}; font-weight: bold; font-size: 12px;`
);
// ========== 暴露调试 API 到全局 ==========
if (typeof window !== 'undefined') {
// 暴露 Socket 类型到全局
window.SOCKET_TYPE = SOCKET_TYPE;
// 暴露调试 API
window.__SOCKET_DEBUG__ = {
// 获取当前连接状态
getStatus: () => {
const isConnected = socket.connected || false;
return {
type: SOCKET_TYPE,
connected: isConnected,
reconnectAttempts: socket.getReconnectAttempts?.() || 0,
maxReconnectAttempts: socket.getMaxReconnectAttempts?.() || Infinity,
service: useMock ? 'mockSocketService' : 'socketService',
};
},
// 手动重连
reconnect: () => {
console.log('[Socket Debug] Manual reconnect triggered');
if (socket.reconnect) {
socket.reconnect();
} else {
socket.disconnect();
socket.connect();
}
},
// 断开连接
disconnect: () => {
console.log('[Socket Debug] Manual disconnect triggered');
socket.disconnect();
},
// 连接
connect: () => {
console.log('[Socket Debug] Manual connect triggered');
socket.connect();
},
// 获取服务实例 (仅用于调试)
getService: () => socket,
// 导出诊断信息
exportDiagnostics: () => {
const status = window.__SOCKET_DEBUG__.getStatus();
const diagnostics = {
...status,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent,
url: window.location.href,
};
console.log('[Socket Diagnostics]', diagnostics);
return diagnostics;
}
};
console.log(
'%c[Socket Debug] Debug API available at window.__SOCKET_DEBUG__',
'color: #2196F3; font-weight: bold;'
);
console.log(
'%cTry: window.__SOCKET_DEBUG__.getStatus()',
'color: #2196F3;'
);
}
export default socket;