Signalr断线重连机制

前言

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

 

解决办法(js)

复制代码
//链接到自己的hub
 var connection = new signalR.HubConnectionBuilder().withUrl("/SignalR/chatHub").build();
 
 //重连方法
const startSignalRConnection = connection => connection.start()
    .then(() => console.info("重连成功!"))
    .catch(err =>
        //  console.error('SignalR Connection Error: ', err)
        layer.alert("即时消息链接已断开,请重新刷新页面"));
 
//启动链接
async function start() {
    try {
        await connection.start().then(function () {
        }).catch(function (err) {
            return console.error(err.toString());
        });
        console.log("connected");
    } catch (err) {
        console.log(err);
        setTimeout(() => start(), 5000);
    }
};
start();
//设置超时时间(30分钟超时)
connection.serverTimeoutInMilliseconds = 30 * 60 * 1000;
//超时时间过了之后会自动断开链接
//链接断开,尝试重连
connection.onclose(() => setTimeout(startSignalRConnection(connection), 5000));
复制代码

 

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

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

后端的代码(C#)

复制代码
            //指定重连间隔:0s,0s,10s
            HubConnection hubConnection = new HubConnectionBuilder()
                .WithUrl(new Uri("http://localhost/chathub"))
                .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(10) })
                .Build(); 
            HubConnectionBuilder hubConnectionBuilder = new HubConnectionBuilder(); 
            //重连
            hubConnectionBuilder = (HubConnectionBuilder)hubConnectionBuilder
               .WithAutomaticReconnect();
            //创建连接对象
            hubConnection = hubConnectionBuilder.Build();
            //断开连接
            hubConnection.Closed += async (exception) =>
            {
            /   await Task.Delay(0);
            };
            //重连中
            hubConnection.Reconnecting += async (exception) =>
            {
                await Task.Delay(0);
            };
            //重连成功
            hubConnection.Reconnected += async (exception) =>
            {
                await Task.Delay(0);
            };
            //心跳检查
            hubConnection.KeepAliveInterval = TimeSpan.FromSeconds(60);
复制代码

 

   根据您的需求选则前端或后端代码!!!

posted @   喆星高照  阅读(975)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示