KKSU
2024-06-19 eaf453b84d916acb702b163ebcb462850daeb591
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
package cc.mrbird.febs.websocket;
 
import cn.hutool.core.util.StrUtil;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
 
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @date 2020-09-01
 **/
public class WsSessionManager {
 
    private static final ConcurrentHashMap<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();
 
    public static void add(String key, WebSocketSession session) {
        SESSIONS.put(key, session);
    }
 
 
    public static WebSocketSession remove(String key) {
        return SESSIONS.remove(key);
    }
 
    public static void removeAndClose(String key) {
        WebSocketSession session = remove(key);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                // todo: 关闭出现异常处理
                e.printStackTrace();
            }
        }
    }
 
    public static WebSocketSession get(String key) {
        // 获得 session
        return SESSIONS.get(key);
    }
 
    /**
     * 发送消息
     *
     * @param key 用户手机号
     * @param msg 消息
     */
    public static void sendMsgToOne(String key, String msg) {
        TextMessage textMessage = new TextMessage(msg);
        try {
            if (SESSIONS.containsKey(key)) {
                SESSIONS.get(key).sendMessage(textMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 批量发送
     *
     * @param keys 手机号集合, 逗号隔开
     * @param msg 消息
     */
    public static void sendMsgToMany(String keys, String msg) {
        TextMessage textMessage = new TextMessage(msg);
 
        List<String> keyList = StrUtil.splitTrim(keys, ",");
        for (Map.Entry<String, WebSocketSession> entry : SESSIONS.entrySet()) {
            if (keyList.contains(entry.getKey())) {
                try {
                    entry.getValue().sendMessage(textMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
}