Signalr断线重连机制

发布时间 2023-10-19 10:37:16作者: 喆星高照

前言

Signalr 即时消息发布到服务器后发现链接老是自动断开,导致无法发送广播
后面百度搜了一下,signalr有个超时的机制

 

解决办法(js)

  1. //链接到自己的hub
  2.  var connection = new signalR.HubConnectionBuilder().withUrl("/SignalR/chatHub").build();
  3.  
  4.  //重连方法
  5. const startSignalRConnection = connection => connection.start()
  6.     .then(() => console.info("重连成功!"))
  7.     .catch(err =>
  8.         //  console.error('SignalR Connection Error: ', err)
  9.         layer.alert("即时消息链接已断开,请重新刷新页面"));
  10.  
  11. //启动链接
  12. async function start() {
  13.     try {
  14.         await connection.start().then(function () {
  15.         }).catch(function (err) {
  16.             return console.error(err.toString());
  17.         });
  18.         console.log("connected");
  19.     } catch (err) {
  20.         console.log(err);
  21.         setTimeout(() => start(), 5000);
  22.     }
  23. };
  24. start();
  25. //设置超时时间(30分钟超时)
  26. connection.serverTimeoutInMilliseconds = 30 * 60 * 1000;
  27. //超时时间过了之后会自动断开链接
  28. //链接断开,尝试重连
  29. connection.onclose(() => setTimeout(startSignalRConnection(connection), 5000));

只需要在断开的时候重连就行了

后端同样也有链接断开,连接中,链接成功的回调,根据需要选择
一般重连在前端展示就行

后端的代码(C#)

  1.             //指定重连间隔:0s,0s,10s
  2.             HubConnection hubConnection = new HubConnectionBuilder()
  3.                 .WithUrl(new Uri("http://localhost/chathub"))
  4.                 .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(10) })
  5.                 .Build(); 
  6.             HubConnectionBuilder hubConnectionBuilder = new HubConnectionBuilder(); 
  7.             //重连
  8.             hubConnectionBuilder = (HubConnectionBuilder)hubConnectionBuilder
  9.                .WithAutomaticReconnect();
  10.             //创建连接对象
  11.             hubConnection = hubConnectionBuilder.Build();
  12.             //断开连接
  13.             hubConnection.Closed += async (exception) =>
  14.             {
  15.             /   await Task.Delay(0);
  16.             };
  17.             //重连中
  18.             hubConnection.Reconnecting += async (exception) =>
  19.             {
  20.                 await Task.Delay(0);
  21.             };
  22.             //重连成功
  23.             hubConnection.Reconnected += async (exception) =>
  24.             {
  25.                 await Task.Delay(0);
  26.             };
  27.             //心跳检查
  28.             hubConnection.KeepAliveInterval = TimeSpan.FromSeconds(60);

按需求选则前端或后端代码