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);
根据您的需求选则前端或后端代码!!!
本文来自博客园,作者:喆星高照,转载请注明原文链接:https://www.cnblogs.com/houxianzhou/p/17774173.html
分类:
javascript
, jqyery
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?