liusuyi
2024-08-12 91b70d5ad2ada85cf00b25f7b9ecd9cf980bf138
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package com.ruoyi.utils.websocket.util;
 
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;
 
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * @ClassName WebSocketUtils
 * @Description: websocket工具类
 * @Author 刘苏义
 * @Date 2023/1/27 7:46
 * @Version 1.0
 */
@Slf4j
public final class WebSocketUtils {
 
    // 存储 websocket session
    public static final ConcurrentMap<String, Session> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();
    //存储房间
    public static final ConcurrentHashMap<String, Set<String>> ROOM_USER_SET = new ConcurrentHashMap<>();
 
    /**
     * @param session 用户 session
     * @param message 发送内容
     */
    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        synchronized (session) {
            try {
                log.debug("发送消息:" + message);
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("sendMessage IOException ", e);
            }
        }
    }
 
    /**
     * @param session 用户 session
     * @param message 发送内容
     */
    public static void sendMessage(Session session, Map message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        synchronized (session) {
            try {
                session.getBasicRemote().sendText(new JSONObject(message).toString());
            } catch (IOException e) {
                log.error("sendMessage IOException ", e);
            }
        }
    }
 
    public static void sendMessage(Session session, List message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        synchronized (session) {
            try {
                session.getBasicRemote().sendText(String.join(", ", message));
            } catch (IOException e) {
                log.error("sendMessage IOException ", e);
            }
        }
    }
 
    /**
     * 推送消息到其他客户端
     *
     * @param message
     */
    public static void sendMessageAll(String message) {
        ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message));
    }
    /**
     * 发送消息给指定用户
     *
     * @param  userId 用户id
     * @param  message 消息内容
     * @author 刘苏义
     * @date   2024/8/12 15:43
     */
    public static void sendMessage(String userId,String message) {
        WebSocketUtils.ONLINE_USER_SESSIONS.get(userId).getAsyncRemote().sendText(message);
    }
    /**
     * 推送消息到其他客户端
     *
     * @param message
     */
    public static void sendMessageAll(Map message) {
        JSONObject jsonObject = new JSONObject(message);
        ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, jsonObject.toString()));
    }
 
    /**
     * 推送消息到当前房间的其他客户端
     *
     * @param message
     */
    public static void sendRoomMessage(String roomId, String message) {
        Set<String> userSet = ROOM_USER_SET.getOrDefault(roomId, new HashSet<>());
        userSet.stream().forEach(userId -> {
            String regex = "^" + Pattern.quote(userId) + "_\\d+$";
            Pattern pattern = Pattern.compile(regex);
            ONLINE_USER_SESSIONS.entrySet().stream().filter(entry -> {
                Matcher matcher = pattern.matcher(entry.getKey());
                return matcher.matches();
            }).map(Map.Entry::getValue).forEach(session -> WebSocketUtils.sendMessage(session, message));
        });
    }
    /**
     * @Author 刘苏义
     * @Description  发送消息给userId_前缀的人
     * @Date   2024/7/16 10:24
     * @Param
     * @return
     */
    public static void sendMessagePrefix(String targetId, String message) {
        String regex = "^" + Pattern.quote(targetId) + "_\\d+$";
        Pattern pattern = Pattern.compile(regex);
        ONLINE_USER_SESSIONS.entrySet().stream().filter(entry -> {
            Matcher matcher = pattern.matcher(entry.getKey());
            return matcher.matches();
        }).map(Map.Entry::getValue).forEach(session -> WebSocketUtils.sendMessage(session, message));
    }
}