Signalr断线重连机制
电脑版发表于:2022/8/15 11:01
前言
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);
按需求选则前端或后端代码