修改signalr的bug
This commit is contained in:
parent
c3ec557c4d
commit
68419bf7de
@ -56,11 +56,11 @@ namespace HHWMS.Web.Controllers
|
||||
}
|
||||
else
|
||||
{
|
||||
var signined = UserSessionManager.IsUserSignined(user.Name);
|
||||
var signined = UserSessionManager.IsUserSignined(user.ITCode);
|
||||
if (signined)
|
||||
{
|
||||
// 踢人下线
|
||||
await KickUser(user.Name);
|
||||
await KickUser(user.ITCode);
|
||||
}
|
||||
//其他属性可以通过user.Attributes["aaa"] = "bbb"方式赋值
|
||||
Wtm.LoginUserInfo = user;
|
||||
@ -85,8 +85,15 @@ namespace HHWMS.Web.Controllers
|
||||
}
|
||||
var principal = user.CreatePrincipal();
|
||||
|
||||
// 确保Principal包含ITCode claim,用于会话验证
|
||||
var identity = principal.Identity as System.Security.Claims.ClaimsIdentity;
|
||||
if (identity != null && !identity.HasClaim(c => c.Type == "ITCode"))
|
||||
{
|
||||
identity.AddClaim(new System.Security.Claims.Claim("ITCode", user.ITCode));
|
||||
}
|
||||
|
||||
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
|
||||
UserSessionManager.AddUserSession(user.Name,principal.Claims.First(c => c.Type == "SessionId").Value);
|
||||
UserSessionManager.AddUserSession(user.ITCode,principal.Claims.First(c => c.Type == "SessionId").Value);
|
||||
return Redirect(HttpUtility.UrlDecode(url));
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,7 +21,9 @@ public class SessionValidationMiddleware
|
||||
{
|
||||
if (context.User.Identity.IsAuthenticated)
|
||||
{
|
||||
var userId = context.User.Identity.Name;
|
||||
// 优先使用ITCode claim,如果不存在则使用Name
|
||||
var userId = context.User.Claims.FirstOrDefault(c => c.Type == "ITCode")?.Value
|
||||
?? context.User.Identity.Name;
|
||||
var sessionId = context.User.Claims.FirstOrDefault(c => c.Type == "SessionId")?.Value;
|
||||
|
||||
if (!UserSessionManager.IsUserSessionValid(userId, sessionId))
|
||||
@ -35,4 +37,4 @@ public class SessionValidationMiddleware
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1 +1,267 @@
|
||||
<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>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user