From e3002cabf60f9798c9597c548a03fbabada98742 Mon Sep 17 00:00:00 2001 From: zhougf Date: Fri, 5 Dec 2025 21:46:33 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=BC=BASignalR=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E7=AE=A1=E7=90=86=EF=BC=8C=E6=B7=BB=E5=8A=A0=E9=87=8D?= =?UTF-8?q?=E8=BF=9E=E6=9C=BA=E5=88=B6=E5=92=8C=E7=8A=B6=E6=80=81=E6=8F=90?= =?UTF-8?q?=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现自定义重连策略,支持最大重连次数限制 - 添加连接丢失和恢复的处理函数 - 显示重连状态和服务不可用提示 - 优化心跳机制和页面可见性下的连接管理 --- HHWMS.Web/Views/Home/Index.cshtml | 160 ++++++++++++++++++++++++++++-- 1 file changed, 150 insertions(+), 10 deletions(-) diff --git a/HHWMS.Web/Views/Home/Index.cshtml b/HHWMS.Web/Views/Home/Index.cshtml index 686cee4..620607b 100644 --- a/HHWMS.Web/Views/Home/Index.cshtml +++ b/HHWMS.Web/Views/Home/Index.cshtml @@ -6,18 +6,34 @@ var heartbeatTimer = null; var userId = '@ViewData["ITCode"]'; // 从后端获取当前用户ID var isForceLogout = false; + + // 服务异常检测 + var reconnectAttempts = 0; // 重连尝试次数 + var maxReconnectAttempts = 5; // 最大重连次数 + var isServerDown = false; // 服务是否宕机 + var serverDownAlertIndex = null; // 服务宕机弹窗索引 + var reconnectTimer = null; // 重连定时器 // 初始化 SignalR 连接 function initLoginHub() { loginConnection = new signalR.HubConnectionBuilder() .withUrl("/loginHub") - .withAutomaticReconnect([0, 2000, 5000, 10000, 30000]) // 自动重连策略 + .withAutomaticReconnect({ + nextRetryDelayInMilliseconds: function(retryContext) { + // 自定义重连策略 + if (retryContext.previousRetryCount < maxReconnectAttempts) { + return Math.min(1000 * Math.pow(2, retryContext.previousRetryCount), 30000); + } + return null; // 停止自动重连 + } + }) .build(); // 监听强制登出事件 loginConnection.on("ForceLogout", function(message) { isForceLogout = true; stopHeartbeat(); + stopReconnect(); // 使用layer弹窗提示 layer.alert(message || "您的账号已在其他设备登录,请重新登录", { @@ -36,6 +52,7 @@ // 监听注册成功 loginConnection.on("RegisterSuccess", function(message) { console.log("SignalR 登录连接成功:", message); + onConnectionRestored(); startHeartbeat(); }); @@ -50,16 +67,21 @@ stopHeartbeat(); if (!isForceLogout) { - // 非强制登出,尝试重连 - setTimeout(function() { - startConnection(); - }, 5000); + onConnectionLost(); } }); + // 正在重连事件 + loginConnection.onreconnecting(function(error) { + console.log("SignalR 正在重连...", error); + reconnectAttempts++; + showReconnectingStatus(); + }); + // 重连成功事件 loginConnection.onreconnected(function(connectionId) { console.log("SignalR 重连成功:", connectionId); + onConnectionRestored(); // 重新注册 if (userId) { loginConnection.invoke("Register", userId).catch(function(err) { @@ -79,6 +101,7 @@ loginConnection.start() .then(function() { console.log("SignalR 连接已建立"); + onConnectionRestored(); // 注册当前用户 if (userId) { loginConnection.invoke("Register", userId).catch(function(err) { @@ -88,13 +111,126 @@ }) .catch(function(err) { console.error("SignalR 连接失败:", err); - // 连接失败,5秒后重试 - setTimeout(function() { - startConnection(); - }, 5000); + reconnectAttempts++; + + if (reconnectAttempts >= maxReconnectAttempts) { + // 达到最大重连次数,显示服务不可用 + showServerDownAlert(); + } else { + // 继续重连 + showReconnectingStatus(); + var delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000); + reconnectTimer = setTimeout(function() { + startConnection(); + }, delay); + } }); } + // 连接丢失处理 + function onConnectionLost() { + reconnectAttempts = 0; + showReconnectingStatus(); + + // 手动启动重连 + reconnectTimer = setTimeout(function() { + startConnection(); + }, 2000); + } + + // 连接恢复处理 + function onConnectionRestored() { + reconnectAttempts = 0; + isServerDown = false; + hideReconnectingStatus(); + hideServerDownAlert(); + } + + // 显示重连中状态 + function showReconnectingStatus() { + if ($('#reconnecting-status').length === 0) { + $('body').append( + '
' + + ' ' + + '正在连接服务器... (尝试 ' + reconnectAttempts + '/' + maxReconnectAttempts + ')' + + '
' + ); + } else { + $('#reconnecting-status').html( + ' ' + + '正在连接服务器... (尝试 ' + reconnectAttempts + '/' + maxReconnectAttempts + ')' + ).show(); + } + } + + // 隐藏重连中状态 + function hideReconnectingStatus() { + $('#reconnecting-status').hide(); + } + + // 显示服务不可用弹窗 + function showServerDownAlert() { + if (isServerDown) return; + isServerDown = true; + hideReconnectingStatus(); + + // 显示服务不可用状态栏 + if ($('#server-down-status').length === 0) { + $('body').append( + '
' + + ' ' + + '服务器连接已断开,请检查网络或联系管理员 ' + + '' + + '
' + ); + } else { + $('#server-down-status').show(); + } + + // 弹窗提示 + if (!serverDownAlertIndex) { + serverDownAlertIndex = layer.confirm('服务器连接已断开,可能是网络问题或服务器维护中。
是否重新连接?', { + icon: 2, + title: "连接异常", + btn: ['重新连接', '稍后再试'], + closeBtn: 0 + }, function(index) { + layer.close(index); + serverDownAlertIndex = null; + manualReconnect(); + }, function(index) { + layer.close(index); + serverDownAlertIndex = null; + }); + } + } + + // 隐藏服务不可用弹窗 + function hideServerDownAlert() { + $('#server-down-status').hide(); + if (serverDownAlertIndex) { + layer.close(serverDownAlertIndex); + serverDownAlertIndex = null; + } + } + + // 手动重连 + function manualReconnect() { + reconnectAttempts = 0; + isServerDown = false; + hideServerDownAlert(); + showReconnectingStatus(); + startConnection(); + } + + // 停止重连 + function stopReconnect() { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + } + // 开始心跳 function startHeartbeat() { stopHeartbeat(); @@ -123,6 +259,8 @@ // 页面关闭时断开连接 $(window).on('beforeunload', function() { + stopReconnect(); + stopHeartbeat(); if (loginConnection) { loginConnection.stop(); } @@ -132,7 +270,9 @@ $(document).on('visibilitychange', function() { if (document.visibilityState === 'visible' && !isForceLogout) { if (loginConnection && loginConnection.state !== signalR.HubConnectionState.Connected) { - startConnection(); + if (!isServerDown) { + manualReconnect(); + } } else if (loginConnection && userId) { // 页面可见时发送一次心跳 loginConnection.invoke("Heartbeat", userId).catch(function(err) {