From 70eff21bd95591b29fabcb95ee3a45508d6037ac Mon Sep 17 00:00:00 2001 From: wzp Date: Tue, 17 Dec 2024 12:36:49 +0800 Subject: [PATCH] fix: fix connection close bug --- .../java/org/mmga/clubs/controller/ChessController.java | 4 ++++ src/main/java/org/mmga/clubs/entities/chess/Room.java | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/mmga/clubs/controller/ChessController.java b/src/main/java/org/mmga/clubs/controller/ChessController.java index ae8d01e..ebc46da 100644 --- a/src/main/java/org/mmga/clubs/controller/ChessController.java +++ b/src/main/java/org/mmga/clubs/controller/ChessController.java @@ -63,6 +63,7 @@ public class ChessController { Optional i = jwtUtils.verifyTokenSafe(token); if (i.isEmpty()) { WebSocketUtils.sendPacket(new ErrorPacket("token验证失败!"), session); + log.info("closed by token verifier"); session.close(); messageQueue.clear(); return; @@ -91,6 +92,7 @@ public class ChessController { WebSocketUtils.sendPacket(roomByPlayer.getRoomInfo(users), session); } Session remove = sessions.remove(existsUser); + log.info("session closed by another session"); remove.close(); } for (String s : messageQueue) { @@ -215,6 +217,7 @@ public class ChessController { log.info("session closed {}", sessionId); sessions.remove(sessionId); users.remove(sessionId); + pingPong.remove(session); } @SneakyThrows @@ -222,6 +225,7 @@ public class ChessController { public static void connectionManager() { for (Session value : sessions.values()) { if (!pingPong.getOrDefault(value, true)) { + log.info("closed by connectionManager"); value.close(); continue; } diff --git a/src/main/java/org/mmga/clubs/entities/chess/Room.java b/src/main/java/org/mmga/clubs/entities/chess/Room.java index 277dc25..775cb71 100644 --- a/src/main/java/org/mmga/clubs/entities/chess/Room.java +++ b/src/main/java/org/mmga/clubs/entities/chess/Room.java @@ -77,15 +77,18 @@ public class Room { public void leave(Session session) { String sessionId = session.getId(); if (Objects.nonNull(this.blackSession) && this.blackSession.getId().equals(sessionId)) { - WebSocketUtils.sendPacket(new PlayerLeavePacket(sessionId), whiteSession); + WebSocketUtils.sendPacketIfPossible(new PlayerLeavePacket(sessionId), whiteSession); this.blackSession = null; this.setState(RoomState.WAITING); } if (Objects.nonNull(this.whiteSession) && this.whiteSession.getId().equals(sessionId)) { - WebSocketUtils.sendPacket(new PlayerLeavePacket(sessionId), blackSession); + WebSocketUtils.sendPacketIfPossible(new PlayerLeavePacket(sessionId), blackSession); this.whiteSession = null; this.setState(RoomState.WAITING); } + if (Objects.isNull(this.blackSession) && Objects.isNull(this.whiteSession)) { + this.setState(RoomState.CREATED); + } } public RoomInfoPacket getRoomInfo(Map users) {