| | |
| | | import java.io.IOException; |
| | | import java.util.*; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.concurrent.Executors; |
| | | import java.util.concurrent.ScheduledExecutorService; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | @Slf4j |
| | | @Component |
| | |
| | | |
| | | // 关键:为每个WebSocketSession分配独立的锁对象,确保写操作同步 |
| | | private final Map<WebSocketSession, Object> sessionLocks = new ConcurrentHashMap<>(); |
| | | |
| | | // 延时任务线程池(单线程,守护线程),用于处理连接关闭后的延时清理 |
| | | private final ScheduledExecutorService delayExecutor = Executors.newSingleThreadScheduledExecutor(runnable -> { |
| | | Thread thread = new Thread(runnable, "websocket-关闭-延迟-线程"); |
| | | thread.setDaemon(true); // 设为守护线程,不阻塞JVM退出 |
| | | return thread; |
| | | }); |
| | | |
| | | /** |
| | | * 连接建立后回调 |
| | |
| | | public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { |
| | | String userId = (String) session.getAttributes().get("userId"); |
| | | if (userId != null) { |
| | | log.info("用户[{}]连接关闭,将延时5秒执行清理操作(给前端刷新缓冲)", userId); |
| | | |
| | | // 延时3秒执行清理逻辑 |
| | | delayExecutor.schedule(() -> { |
| | | try { |
| | | |
| | | userSessions.remove(userId); |
| | | sessionLocks.remove(session); // 移除会话锁 |
| | | // 关闭远程调试模式,暂时写死sn,后续改为动态获取sn |
| | | ResponseResult responseResult = _controlService.controlDock("7CTDLCE00A1UPE","debug_mode_close",null); |
| | | log.info("关闭远程调试模式"); |
| | | if(responseResult.getCode() == ResponseResult.CODE_SUCCESS){ |
| | | log.info("关闭远程调试模式成功"); |
| | | } |
| | | // ResponseResult responseResult = _controlService.controlDock("7CTDLCE00A1UPE","debug_mode_close",null); |
| | | // log.info("关闭远程调试模式"); |
| | | // if(responseResult.getCode() == ResponseResult.CODE_SUCCESS){ |
| | | // log.info("关闭远程调试模式成功"); |
| | | // } |
| | | // 清除该用户的所有订阅 |
| | | removeUserAllSubscriptions(userId); |
| | | //System.out.println("用户[" + userId + "]已断开连接,当前在线人数:" + userSessions.size()); |
| | | log.info("用户[{}]已断开连接,当前在线人数:{}", userId, userSessions.size()); |
| | | // log.info("用户[{}]已断开连接,当前在线人数:{}", userId, userSessions.size()); |
| | | log.info("用户[{}]延时5秒清理完成,当前在线人数:{}", userId, userSessions.size()); |
| | | } catch (Exception e) { |
| | | log.error("用户[{}]延时清理操作异常", userId, e); |
| | | } |
| | | }, 5, TimeUnit.SECONDS); // 延时5秒执行 |
| | | } |
| | | else { |
| | | // 无认证用户,直接清理会话锁(无需延时) |
| | | sessionLocks.remove(session); |
| | | log.info("无认证用户连接关闭,直接清理会话锁"); |
| | | } |
| | | } |
| | | |