diff --git a/src/main/java/com/zhangshu/chat/demo/websocket/ChatRoom.java b/src/main/java/com/zhangshu/chat/demo/websocket/ChatRoom.java index f4f03c6..1a1a3c4 100644 --- a/src/main/java/com/zhangshu/chat/demo/websocket/ChatRoom.java +++ b/src/main/java/com/zhangshu/chat/demo/websocket/ChatRoom.java @@ -12,6 +12,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; import javax.websocket.*; import javax.websocket.server.PathParam; @@ -47,7 +48,7 @@ public class ChatRoom { if (Objects.isNull(userPrincipal)) { this.sendMessage("用户验证失败,拒绝连接", session); } - UserDetailsImpl userInfo = (UserDetailsImpl)((Authentication) userPrincipal).getPrincipal(); + UserDetailsImpl userInfo = (UserDetailsImpl) ((Authentication) userPrincipal).getPrincipal(); if (Objects.isNull(userInfo) || !getRoomCache().isExistUser(userInfo.getId())) { this.sendMessage("用户验证失败或者房间内无此用户,拒绝连接", session); return; @@ -75,8 +76,12 @@ public class ChatRoom { if (Objects.isNull(room)) { return; } - UserDetailsImpl userInfo = (UserDetailsImpl) session.getUserPrincipal(); - if (Objects.isNull(userInfo)) { + Principal userPrincipal = session.getUserPrincipal(); + if (Objects.isNull(userPrincipal)) { + return; + } + UserDetailsImpl userInfo = (UserDetailsImpl) ((Authentication) userPrincipal).getPrincipal(); + if (Objects.isNull(userInfo) || !getRoomCache().isExistUser(userInfo.getId())) { return; } UserMessageVo messageVo = UserMessageVo.builder() @@ -124,7 +129,7 @@ public class ChatRoom { String sessionId = session.getId().toLowerCase(); SESSION_CACHE.remove(sessionId); List sessionList = ROOM_SESSION_MAP.get(roomId); - if (sessionList.size() <= 1) { + if (CollectionUtils.isEmpty(sessionList) || sessionList.size() <= 1) { ROOM_SESSION_MAP.remove(roomId); } else { sessionList.remove(sessionId); @@ -143,7 +148,7 @@ public class ChatRoom { String sessionId = session.getId().toLowerCase(); SESSION_CACHE.remove(sessionId); List sessionList = ROOM_SESSION_MAP.get(roomId); - if (sessionList.size() <= 1) { + if (CollectionUtils.isEmpty(sessionList) || sessionList.size() <= 1) { ROOM_SESSION_MAP.remove(roomId); } else { sessionList.remove(sessionId);