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

Angular 8中SignalR自动断开连接事件捕获问题

SignalR 服务器宕机/Socket断开事件捕获方案

客户端侧捕获断开事件

  • JavaScript客户端:绑定onclose事件,连接断开(含服务器宕机、网络中断)时触发,可直接在回调内执行存储逻辑:
    const connection = new signalR.HubConnectionBuilder()
      .withUrl("/chatHub")
      .build();
    
    connection.onclose(async (error) => {
      // 写入你的存储逻辑,比如存本地存储或上报后端
      console.log("连接断开", error);
      // 可选:实现自动重连
      await startConnection();
    });
    
    async function startConnection() {
      try {
        await connection.start();
      } catch (err) {
        setTimeout(startConnection, 5000);
      }
    }
    
  • .NET客户端:绑定Closed事件处理:
    var connection = new HubConnectionBuilder()
        .WithUrl("https://your-domain/hub")
        .Build();
    
    connection.Closed += async (error) =>
    {
        // 执行存储操作,如写入数据库或本地日志
        await LogDisconnectEvent(Context.ConnectionId, error?.Message ?? "正常断开");
        await Task.Delay(5000);
        await connection.StartAsync();
    };
    

服务器侧捕获断开事件

在Hub类中重写OnDisconnectedAsync方法,客户端断开(含服务器主动断开、异常离线)时触发,直接在这里处理存储:

public class YourHub : Hub
{
    private readonly IYourStorageService _storageService;

    public YourHub(IYourStorageService storageService)
    {
        _storageService = storageService;
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        try
        {
            var disconnectMsg = exception != null ? $"异常断开:{exception.Message}" : "正常断开";
            await _storageService.SaveDisconnectRecord(Context.ConnectionId, disconnectMsg);
        }
        catch (Exception ex)
        {
            // 捕获存储操作本身的异常,避免影响基础断开逻辑
            Console.WriteLine($"存储断开事件失败:{ex.Message}");
        }

        await base.OnDisconnectedAsync(exception);
    }
}

日志可见但存储失效的排查要点

  • 检查存储服务的依赖注入是否正确,是否存在实例化失败的情况
  • 确认OnDisconnectedAsync内的异步操作已被正确await,避免异步任务未完成就结束方法
  • 在存储逻辑块添加try-catch,排查是否有被吞掉的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:19:55