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

如何检测Asp.Net Core 6中SignalR裸WebSocket客户端网络连接丢失

检测SignalR ConnectionHandler客户端断开连接的方法

1. 重写ConnectionHandler的OnDisconnectedAsync方法

你的SocialWeatherConnectionHandler继承自ConnectionHandler<T>,可以通过重写OnDisconnectedAsync方法捕获所有客户端断开事件——无论客户端是主动发起断开,还是因网络异常、超时导致被动断开,该方法都会被触发。

示例代码:

public class SocialWeatherConnectionHandler : ConnectionHandler<CustomConnectionState>
{
    private readonly ILogger<SocialWeatherConnectionHandler> _logger;

    public SocialWeatherConnectionHandler(ILogger<SocialWeatherConnectionHandler> logger)
    {
        _logger = logger;
    }

    // 可选:重写OnConnectedAsync记录连接建立事件
    public override async Task OnConnectedAsync(ConnectionContext connection)
    {
        _logger.LogInformation($"客户端[{connection.ConnectionId}]已建立连接");
        await base.OnConnectedAsync(connection);
    }

    public override async Task OnDisconnectedAsync(ConnectionContext connection, Exception? exception)
    {
        // 根据exception判断断开类型
        if (exception != null)
        {
            _logger.LogError(exception, $"客户端[{connection.ConnectionId}]异常断开");
        }
        else
        {
            _logger.LogInformation($"客户端[{connection.ConnectionId}]主动断开");
        }

        // 此处添加断开后的业务逻辑:比如清理连接资源、通知其他客户端等
        await base.OnDisconnectedAsync(connection, exception);
    }
}

// 可选自定义连接状态类,用于存储客户端额外信息(如用户ID、连接时间)
public class CustomConnectionState
{
    public string? UserId { get; set; }
    public DateTime ConnectTime { get; set; } = DateTime.Now;
}

2. 优化SignalR超时与心跳配置

你当前设置了ClientTimeoutInterval = 7秒,需配合KeepAliveInterval确保服务器能准确检测客户端离线:

  • KeepAliveInterval是服务器向客户端发送心跳包的间隔,需小于ClientTimeoutInterval的2/3(避免网络延迟导致误判)。
  • 调整后的配置示例:
builder.Services.AddSignalR(options =>
{
    options.ClientTimeoutInterval = TimeSpan.FromSeconds(7);
    options.KeepAliveInterval = TimeSpan.FromSeconds(4); // 心跳间隔需小于超时时间的2/3
});

当客户端网络断开后,服务器若在连续两个心跳周期未收到响应,会触发OnDisconnectedAsync方法。

关键说明

  • ConnectionContext.ConnectionId是每个客户端连接的唯一标识,可用于追踪特定客户端状态。
  • OnDisconnectedAsync的exception参数:不为空表示异常断开(如网络中断、消息处理错误),为空表示客户端主动调用断开接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:15:25