Xiajijian
2025-10-16 ac3bb8910dd285b9d49844f496ba1ff3dab55bab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.ard.work.component.websocket;
 
import com.ard.work.component.websocket.utils.WebSocketUtil;
import org.springframework.web.socket.WebSocketSession;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
 
public class WebSocketSessionManager {
    private static final ConcurrentMap<Long, WebSocketSession> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();
 
    public static void addSession(Long userId, WebSocketSession session) {
        ONLINE_USER_SESSIONS.put(userId, session);
    }
 
    public static void removeSession(Long userId) {
        ONLINE_USER_SESSIONS.remove(userId);
    }
 
    public static WebSocketSession getSession(Long userId) {
        return ONLINE_USER_SESSIONS.get(userId);
    }
 
    public static void broadcast(String message) {
        ONLINE_USER_SESSIONS.forEach((userId, session) -> WebSocketUtil.sendMessage(session, message));
    }
 
    //返回当前在线用户数
    public static int getOnlineUserCount() {
        return ONLINE_USER_SESSIONS.size();
    }
}