zhaowenyu
2025-11-29 8b459796efa4f1e0571f4436953a52d25a063e70
ard-sample/src/main/java/com/ard/sample/component/websocket/handler/DockWebSocketHandler.java
@@ -1,11 +1,12 @@
package com.ard.sample.component.websocket.handler;
import com.alibaba.fastjson2.JSON;
import com.ard.sample.common.model.ResponseResult;
import com.ard.sample.component.websocket.enums.MessageType;
import com.ard.sample.component.websocket.model.Payload;
import com.ard.sample.component.websocket.model.WebSocketMessage;
import com.ard.sample.manage.service.IControlService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
@@ -16,6 +17,9 @@
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
@@ -23,6 +27,9 @@
    @Autowired
    private LiveStreamHandler _liveStreamService;
    @Autowired
    private IControlService _controlService;
    // 存储用户会话:userId -> WebSocketSession
    private final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();
@@ -32,6 +39,13 @@
    // 关键:为每个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;
    });
    /**
     * 连接建立后回调
@@ -87,7 +101,6 @@
    private void handleSubscription(String userId, String type, Payload payload) {
        String sn = payload.getSn();
        boolean subscribe = payload.isSubscribe();
        String videoType = payload.getVideotype();
        String subscriptionKey = getSubscriptionKey(sn, type); // 生成唯一订阅标识
        if (subscribe) {
@@ -99,14 +112,15 @@
                // 开启直播
                // 开启直播逻辑
                System.out.println("开启直播");
                _liveStreamService.StartLiveStreaming(sn, videoType);
                _liveStreamService.StartLiveStreaming(sn);
            }
        } else {
            // 停止直播
            if(MessageType.LIVESTREAM.getType().equals(type)){
                System.out.println("停止直播");
                _liveStreamService.StopLiveStreaming(sn);
            }
            // 停止直播--前端不主动关注直播,则在断开连接时停止
//            if(MessageType.LIVESTREAM.getType().equals(type)){
//                System.out.println("停止直播");
//
//                _liveStreamService.StopLiveStreaming(sn);
//            }
            // 取消订阅操作
            if (subscriptions.containsKey(subscriptionKey)) {
                subscriptions.get(subscriptionKey).remove(userId);
@@ -126,12 +140,34 @@
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = (String) session.getAttributes().get("userId");
        if (userId != null) {
            userSessions.remove(userId);
            sessionLocks.remove(session); // 移除会话锁
            // 清除该用户的所有订阅
            removeUserAllSubscriptions(userId);
            //System.out.println("用户[" + userId + "]已断开连接,当前在线人数:" + userSessions.size());
            log.info("用户[{}]已断开连接,当前在线人数:{}", userId, userSessions.size());
            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("关闭远程调试模式成功");
        //            }
                    // 清除该用户的所有订阅
                    removeUserAllSubscriptions(userId);
                    //System.out.println("用户[" + 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("无认证用户连接关闭,直接清理会话锁");
        }
    }
@@ -140,8 +176,13 @@
     */
    private void removeUserAllSubscriptions(String userId) {
        for (Map.Entry<String, Set<String>> entry : subscriptions.entrySet()) {
            // 停止直播逻辑
            entry.getValue().remove(userId);
            if (entry.getValue().isEmpty()) {
                if (entry.getKey().contains(MessageType.LIVESTREAM.getType())) {
                    String sn = entry.getKey().split(":")[0];
                    _liveStreamService.StopLiveStreaming(sn);
                }
                subscriptions.remove(entry.getKey());
            }
        }