zhuguifei
2026-03-10 58402bd5e762361363a0f7d7907153c77dbb819f
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.shlanbao.tzsc.pms.websocket;
 
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
 
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 *
 */
public class WebSocketSessionUtils {
    private static WebSocketSessionUtils instance = new WebSocketSessionUtils();
 
    private WebSocketSessionUtils() {
    }
 
    public static WebSocketSessionUtils getInstance() {
        return instance;
    }
 
    private Map<String, WebSocketSession> clients = new ConcurrentHashMap<String, WebSocketSession>();
 
 
    /**
     * <p>记录一个连接</p>
     *
     * @param userId
     * @param webSocketSession
     */
    public void add(String userId, WebSocketSession webSocketSession) {
        if (userId == null||webSocketSession==null){
            System.err.println("websocket:用户名或session为空,无法建立正常连接");
        }
        if (clients.containsKey(userId)) {
            clients.remove(userId);
        }
        clients.put(userId, webSocketSession);
    }
 
    /**
     * <p>通过id获取连接</p>
     *
     * @param userId
     * @return
     */
    public WebSocketSession get(String userId) {
        return clients.get(userId);
    }
 
    /**
     * <p>移除连接</p>
     *
     * @param userId
     */
    public void remove(String userId) {
        if (userId == null) return;
        clients.remove(userId);
    }
 
    public int size() {
        return clients.size();
    }
 
    public void sendMessageToTarget(String userId, TextMessage message) {
        if (userId == null) return;
        WebSocketSession webSocketSession = clients.get(userId);
        sendMessage(message, webSocketSession);
    }
 
    private void sendMessage(TextMessage message, WebSocketSession webSocketSession) {
        if (webSocketSession != null) {
            if (webSocketSession.isOpen()) {
                try {
                    webSocketSession.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public void sendMessageToAllTarget(TextMessage message) {
        Iterator iterator = clients.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry enter = (Map.Entry) iterator.next();
            WebSocketSession ws = clients.get(enter.getKey());
            sendMessage(message, ws);
        }
    }
 
    public Map<String, WebSocketSession> getClients() {
        return clients;
    }
}