Signalr断线重连机制

6671人阅读 2022/8/15 11:01 总访问:651539 评论:0 收藏:0 手机
分类: .net core

前言

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);

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

评价
脚踏实地,一步一个脚印
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术