You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socket.IO忽略自定义重连延迟,始终以5000ms重连的问题

Socket.IO自定义重连延迟不生效的解决方案

问题根源

你当前使用的SocketIOClient库自带自动重连逻辑可能存在配置不生效的情况,或是版本兼容性问题,导致ReconnectionDelay和RandomizationFactor设置未被正确应用,始终使用默认的5000ms重连间隔。

解决方法

方案1:手动控制重连逻辑(最可靠)

关闭库的自动重连,在断开连接时自行计算随机延迟并触发重连,完全掌控重连间隔:

修改代码步骤:

  1. 在SocketIOOptions中关闭自动重连:Reconnection = false
  2. 实现自定义重连方法,加入随机延迟逻辑
  3. 在OnDisconnected和OnError事件中调用自定义重连方法

修改后的关键代码:

public static async Task StartSocketIOListenerAsync()
{
    if (_isConnected)
    {
        StreamLogger.Info("Socket.IO Listener is already running.");
        return;
    }

    StreamLogger.Info("Initializing Socket.IO Connection...");
    var options = new SocketIOOptions
    {
        Reconnection = false, // 关闭自动重连
        Transport = SocketIOClient.Transport.TransportProtocol.WebSocket,
        ExtraHeaders = new Dictionary<string, string>
        {
            { "X-Token", _authToken },
            { "X-Computer-Name", _computerName }
        }
    };

    _socket = new SocketIOClient.SocketIO(_serverUrl, options);

    _socket.OnConnected += (sender, e) =>
    {
        _isConnected = true;
        _reconnectAttempts = 0;
        ConnectionStatusChanged?.Invoke(null, true);
        StreamLogger.Info("Socket.IO Connected.");
    };

    _socket.OnDisconnected += async (sender, e) =>
    {
        _isConnected = false;
        ConnectionStatusChanged?.Invoke(null, false);
        StreamLogger.Warning($"Socket.IO Disconnected: {e}");
        await CustomReconnectAsync();
    };

    _socket.OnError += async (sender, e) =>
    {
        _isConnected = false;
        ConnectionStatusChanged?.Invoke(null, false);
        StreamLogger.Error($"Socket.IO Connection Error: {e}");
        await CustomReconnectAsync();
    };

    SubscribeToEvents();
    await _socket.ConnectAsync();
}

private static async Task CustomReconnectAsync()
{
    _reconnectAttempts++;
    // 计算5000-30000ms的随机延迟
    int delay = _random.Next(5000, 30001);
    StreamLogger.Info($"Waiting {delay}ms before reconnect attempt {_reconnectAttempts}...");
    await Task.Delay(delay);
    
    try
    {
        await _socket.ConnectAsync();
    }
    catch (Exception ex)
    {
        StreamLogger.Error($"Reconnect attempt {_reconnectAttempts} failed: {ex.Message}");
        await CustomReconnectAsync(); // 触发下一次重连
    }
}

方案2:修正库自带配置的使用

如果坚持使用库的自动重连,先升级SocketIOClient到最新稳定版,再调整配置参数:
库的重连延迟计算公式为ReconnectionDelay ± (ReconnectionDelay * RandomizationFactor),要实现5000-30000ms的范围,可以设置:

ReconnectionDelay = 17500, // 中间基准值
RandomizationFactor = 0.714f, // (30000-17500)/17500 ≈ 0.714

这种方式依赖库的实现逻辑,稳定性不如手动控制。

注意事项

  • 手动重连时加入日志,方便排查重连失败问题
  • 可根据需求添加最大重试次数限制,避免无限递归
  • 2000个客户端场景下,随机延迟能有效避免雪崩式重连,手动控制逻辑更稳定

内容的提问来源于stack exchange,提问作者Glenn Angel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 20:23:11