webSocket清除

This commit is contained in:
caozehui
2026-06-09 14:48:12 +08:00
parent 212f1295eb
commit 29ddc8c2de
2 changed files with 14 additions and 4 deletions

View File

@@ -87,6 +87,16 @@ public class WebServiceManager {
return userSessions.remove(userId);
}
/**
* 仅当当前会话仍绑定到指定通道时才移除,避免旧连接误删新连接映射。
*/
public static boolean removeByUserId(String userId, Channel channel) {
if (userId == null || channel == null) {
return false;
}
return userSessions.remove(userId, channel);
}
/**
* 根据channelId移除会话兼容老版本
* 时间复杂度O(n)建议使用removeByUserId替代

View File

@@ -111,7 +111,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
public void handlerRemoved(ChannelHandlerContext ctx) {
log.info("webSocket客户端退出channelId: {}, userId: {}", ctx.channel().id(), this.userId);
if (this.userId != null) {
WebServiceManager.removeByUserId(this.userId);
WebServiceManager.removeByUserId(this.userId, ctx.channel());
} else {
// 备用方案如果userId为空使用传统方法
WebServiceManager.removeChannel(ctx.channel().id().toString());
@@ -168,7 +168,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
log.error("客户端心跳检测空闲次数超过{}次关闭连接channelId: {}, userId: {}", MAX_HEARTBEAT_MISS_COUNT, ctx.channel().id(), this.userId);
ctx.channel().close();
if (this.userId != null) {
WebServiceManager.removeByUserId(this.userId);
WebServiceManager.removeByUserId(this.userId, ctx.channel());
} else {
WebServiceManager.removeChannel(ctx.channel().id().toString());
}
@@ -326,7 +326,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
// 清理会话
if (this.userId != null) {
WebServiceManager.removeByUserId(this.userId);
WebServiceManager.removeByUserId(this.userId, ctx.channel());
log.debug("已清理WebSocket会话userId: {}, channelId: {}", this.userId, channelId);
} else {
WebServiceManager.removeChannel(channelId);
@@ -427,4 +427,4 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
}
// ================================ URL解析工具已移至WebSocketPreprocessor ================================
}
}