268 lines
9.8 KiB
Plaintext
268 lines
9.8 KiB
Plaintext
<script>layui.use('index')</script>
|
||
<script src="/front/signalr.min.js"></script>
|
||
<script>
|
||
// 全局变量(新增关键标记)
|
||
let loginConnection = null;
|
||
let heartbeatTimer = null;
|
||
let reconnectTimer = null;
|
||
const userId = '@ViewData["ITCode"]';
|
||
let isForceLogout = false;
|
||
let isManualStop = false; // 标记是否主动调用stop(),解决竞态条件
|
||
let registerRetryCount = 0; // Register方法重试次数
|
||
const maxRegisterRetries = 2; // Register最大重试次数
|
||
let heartbeatFailureCount = 0; // 心跳失败计数
|
||
const maxHeartbeatFailures = 3; // 最大心跳失败次数
|
||
let connectionRetryCount = 0; // 连接重试计数
|
||
const maxConnectionRetries = 5; // 最大连接重试次数
|
||
|
||
// 初始化SignalR连接
|
||
function initLoginHub() {
|
||
if (loginConnection) {
|
||
// 主动停止前标记 + 移除监听器,避免onclose触发
|
||
isManualStop = true;
|
||
try {
|
||
loginConnection.off('ForceLogout');
|
||
loginConnection.off('RegisterSuccess');
|
||
loginConnection.off('HeartbeatResponse');
|
||
loginConnection.off('close'); // 移除onclose监听器
|
||
stopHeartbeat();
|
||
loginConnection.stop();
|
||
} catch (err) {
|
||
console.error("销毁旧连接失败:", err);
|
||
} finally {
|
||
isManualStop = false; // 恢复标记
|
||
loginConnection = null;
|
||
}
|
||
}
|
||
|
||
if (!userId) {
|
||
console.warn("用户未登录,跳过SignalR初始化");
|
||
return;
|
||
}
|
||
|
||
loginConnection = new signalR.HubConnectionBuilder()
|
||
.withUrl("/loginHub", { timeout: 10000 })
|
||
.build();
|
||
|
||
registerHubEvents(); // 重新注册监听器
|
||
startConnection();
|
||
}
|
||
|
||
// 注册Hub事件(核心:区分主动/被动断开)
|
||
function registerHubEvents() {
|
||
// 强制登出事件
|
||
loginConnection.on("ForceLogout", (message) => {
|
||
isForceLogout = true;
|
||
stopAllResources(true); // 主动停止,避免onclose触发重定向
|
||
layer.alert(message || "您的账号已在其他设备登录,请重新登录", {
|
||
icon: 0,
|
||
title: "登录提示",
|
||
closeBtn: 0,
|
||
btn: ['确定'],
|
||
yes: (index) => {
|
||
layer.close(index);
|
||
window.location.href = '/Login/Login';
|
||
}
|
||
});
|
||
});
|
||
|
||
// 注册成功事件
|
||
loginConnection.on("RegisterSuccess", (message) => {
|
||
console.log("SignalR注册成功:", message);
|
||
registerRetryCount = 0; // 重置重试次数
|
||
connectionRetryCount = 0; // 重置连接重试次数
|
||
heartbeatFailureCount = 0; // 重置心跳失败次数
|
||
startHeartbeat();
|
||
});
|
||
|
||
// 心跳响应事件
|
||
loginConnection.on("HeartbeatResponse", (serverTime) => {
|
||
console.debug("心跳响应:", serverTime);
|
||
heartbeatFailureCount = 0; // 心跳成功,重置失败计数
|
||
});
|
||
|
||
// 连接关闭事件(核心:区分主动/被动断开)
|
||
loginConnection.onclose((error) => {
|
||
console.log("SignalR连接关闭:", error);
|
||
stopHeartbeat();
|
||
|
||
// 1. 主动停止(如initLoginHub中销毁旧连接):不处理
|
||
if (isManualStop || isForceLogout) return;
|
||
|
||
// 2. 被动断开:尝试重连而不是立即踢下线
|
||
attemptReconnect();
|
||
});
|
||
}
|
||
|
||
// 启动连接(修复stop()竞态 + Register失败处理)
|
||
async function startConnection() {
|
||
if (isForceLogout || !loginConnection) return;
|
||
|
||
// 状态检查:非Disconnected时主动停止
|
||
if (loginConnection.state !== signalR.HubConnectionState.Disconnected) {
|
||
console.log("SignalR当前状态:", loginConnection.state, ",主动停止旧连接");
|
||
isManualStop = true; // 标记主动停止
|
||
try {
|
||
// 移除onclose监听器,避免stop()触发
|
||
loginConnection.off('close');
|
||
await loginConnection.stop();
|
||
} catch (err) {
|
||
console.error("停止旧连接失败:", err);
|
||
} finally {
|
||
isManualStop = false; // 恢复标记
|
||
registerHubEvents(); // 重新注册监听器
|
||
}
|
||
}
|
||
|
||
try {
|
||
await loginConnection.start();
|
||
console.log("SignalR连接建立成功");
|
||
|
||
// 调用Register方法(关键:失败后重试/重定向)
|
||
const registerSuccess = await tryRegisterUser();
|
||
if (!registerSuccess) {
|
||
// Register失败视为连接失败,主动断开 + 重定向
|
||
isManualStop = true;
|
||
await loginConnection.stop();
|
||
isManualStop = false;
|
||
layer.alert('即时通信服务注册失败,请重新登录', {
|
||
icon: 2,
|
||
title: "服务异常",
|
||
closeBtn: 0,
|
||
yes: () => window.location.href = '/Login/Login'
|
||
});
|
||
}
|
||
} catch (err) {
|
||
console.error("SignalR连接启动失败:", err);
|
||
if (!isForceLogout) {
|
||
window.location.href = '/Login/Login';
|
||
}
|
||
}
|
||
}
|
||
|
||
// Register方法重试逻辑(核心修复:失败处理)
|
||
async function tryRegisterUser() {
|
||
if (!loginConnection || loginConnection.state !== signalR.HubConnectionState.Connected) {
|
||
console.warn("连接未就绪,无法注册用户");
|
||
return false;
|
||
}
|
||
|
||
try {
|
||
await loginConnection.invoke("Register", userId);
|
||
return true; // 注册成功
|
||
} catch (err) {
|
||
console.error(`Register调用失败(第${registerRetryCount+1}次):`, err);
|
||
registerRetryCount++;
|
||
|
||
// 未达最大重试次数则延迟重试
|
||
if (registerRetryCount < maxRegisterRetries) {
|
||
await new Promise(resolve => setTimeout(resolve, 1000 * registerRetryCount));
|
||
return tryRegisterUser(); // 递归重试
|
||
}
|
||
|
||
// 重试耗尽,注册失败
|
||
layer.msg(`即时通信注册失败:${err.message}`, {icon: 2, time: 3000});
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// 心跳管理
|
||
function startHeartbeat() {
|
||
stopHeartbeat();
|
||
heartbeatTimer = setInterval(() => {
|
||
if (loginConnection && loginConnection.state === signalR.HubConnectionState.Connected) {
|
||
loginConnection.invoke("Heartbeat", userId).catch((err) => {
|
||
console.error("心跳发送失败:", err);
|
||
heartbeatFailureCount++;
|
||
|
||
// 达到最大失败次数才视为连接异常
|
||
if (heartbeatFailureCount >= maxHeartbeatFailures) {
|
||
console.log("心跳连续失败次数过多,尝试重新连接");
|
||
attemptReconnect();
|
||
} else {
|
||
console.warn(`心跳失败(${heartbeatFailureCount}/${maxHeartbeatFailures}),继续尝试`);
|
||
}
|
||
});
|
||
}
|
||
}, 30000);
|
||
}
|
||
|
||
function stopHeartbeat() {
|
||
if (heartbeatTimer) {
|
||
clearInterval(heartbeatTimer);
|
||
heartbeatTimer = null;
|
||
}
|
||
}
|
||
|
||
// 重连机制
|
||
function attemptReconnect() {
|
||
if (isForceLogout || isManualStop) return;
|
||
|
||
if (connectionRetryCount >= maxConnectionRetries) {
|
||
console.log("连接重试次数已达上限,跳转登录页");
|
||
layer.alert('与服务器的连接多次失败,请重新登录', {
|
||
icon: 2,
|
||
title: "连接异常",
|
||
closeBtn: 0,
|
||
btn: ['确定'],
|
||
yes: (index) => {
|
||
layer.close(index);
|
||
window.location.href = '/Login/Login';
|
||
},
|
||
end: () => {
|
||
window.location.href = '/Login/Login';
|
||
}
|
||
});
|
||
return;
|
||
}
|
||
|
||
connectionRetryCount++;
|
||
const delay = Math.min(1000 * Math.pow(2, connectionRetryCount), 30000); // 指数退避,最大30秒
|
||
|
||
console.log(`第${connectionRetryCount}次重连尝试,${delay/1000}秒后执行`);
|
||
|
||
reconnectTimer = setTimeout(() => {
|
||
if (!isForceLogout && !isManualStop) {
|
||
console.log("开始重连...");
|
||
initLoginHub(); // 重新初始化连接
|
||
}
|
||
}, delay);
|
||
}
|
||
|
||
// 资源清理(支持标记主动停止)
|
||
async function stopAllResources(isManual = false) {
|
||
isManualStop = isManual; // 标记主动停止
|
||
|
||
// 清理重连定时器
|
||
if (reconnectTimer) {
|
||
clearTimeout(reconnectTimer);
|
||
reconnectTimer = null;
|
||
}
|
||
|
||
stopHeartbeat();
|
||
|
||
if (loginConnection) {
|
||
try {
|
||
loginConnection.off('close'); // 移除监听器避免竞态
|
||
await loginConnection.stop();
|
||
} catch (err) {
|
||
console.error("停止连接失败:", err);
|
||
} finally {
|
||
loginConnection = null;
|
||
isManualStop = false; // 恢复标记
|
||
}
|
||
}
|
||
}
|
||
|
||
// 页面生命周期
|
||
$(document).ready(() => {
|
||
if (userId) {
|
||
initLoginHub();
|
||
}
|
||
|
||
window.addEventListener('beforeunload', async (e) => {
|
||
await stopAllResources(true); // 主动停止,避免onclose触发
|
||
});
|
||
});
|
||
</script>
|