fix: ASW-148 断开连接后关闭检测线程

This commit is contained in:
zhangshuai
2024-11-08 14:58:48 +08:00
parent c83e56fc80
commit e5ed7cf47b

View File

@@ -64,14 +64,15 @@ public class EnvironmentNovncWebSocketHandler extends TextWebSocketHandler {
this.userId = (String) session.getAttributes().get("userId");
Constants.ENV_NOVNC_WEBSOCKET_SESSION.put(sessionId, session);
lastReceivedTime = System.currentTimeMillis(); // 初始化接收时间
startConnectionMonitor(session);
Thread checkSessionTimeout = startConnectionMonitor(session);
session.getAttributes().put("checkSessionTimeoutThread", checkSessionTimeout);
}
private void startConnectionMonitor(WebSocketSession session) {
Thread.ofVirtual().start(() -> {
private Thread startConnectionMonitor(WebSocketSession session) {
Thread thread = Thread.ofVirtual().start(() -> {
while (true) {
if (System.currentTimeMillis() - lastReceivedTime > sessionTimeout) {
try {
try {
if (System.currentTimeMillis() - lastReceivedTime > sessionTimeout) {
if (session.isOpen()) {
log.info("current no connection info, clean no real use connection finshed, sessionId: {}", sessionId);
@@ -83,14 +84,17 @@ public class EnvironmentNovncWebSocketHandler extends TextWebSocketHandler {
session.close(CloseStatus.NORMAL.withReason("current no connection info, clean no real use connection finshed."));
break;
}
// 每5分钟检查一次
Thread.sleep(300000);
} catch (Exception e) {
log.error(e, "Error clean no real use connection");
}
Thread.sleep(300000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} catch (IOException e) {
log.error(e, "Error clean no real use connection");
}
}
});
return thread;
}
@@ -188,6 +192,11 @@ public class EnvironmentNovncWebSocketHandler extends TextWebSocketHandler {
if (envWebsocket != null) {
envWebsocket.sendClose(WebSocket.NORMAL_CLOSURE, "Normal closure");
}
Thread checkSessionTimeoutThread = (Thread) session.getAttributes().get("checkSessionTimeoutThread");
if (checkSessionTimeoutThread != null) {
checkSessionTimeoutThread.interrupt();
}
Constants.ENV_NOVNC_WEBSOCKET_SESSION.remove(sessionId);
super.afterConnectionClosed(session, status);
}