| | |
| | | public final class WebSocketUtil { |
| | | |
| | | // 存储 websocket session |
| | | public static final ConcurrentMap<String, WebSocketSession> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>(); |
| | | // 存储 拉流 websocket session |
| | | public static final ConcurrentMap<String, WebSocketSession> STREAM_ONLINE_USER_SESSIONS = new ConcurrentHashMap<>(); |
| | | |
| | | public static final ConcurrentMap<Long, WebSocketSession> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>(); |
| | | /** |
| | | * @param session 用户 session |
| | | * @param message 发送内容 |
| | |
| | | } |
| | | } |
| | | |
| | | public static void sendMessage(Long userId, String message) { |
| | | WebSocketSession session = ONLINE_USER_SESSIONS.get(userId); |
| | | sendMessage(session, message); |
| | | } |
| | | |
| | | /** |
| | | * @param session 用户 session |
| | | * @param message 发送内容 |
| | |
| | | if (session == null) { |
| | | return; |
| | | } |
| | | final InetSocketAddress remoteAddress = session.getRemoteAddress(); |
| | | final InetSocketAddress remoteAddress = session.getRemoteAddress(); |
| | | if (remoteAddress == null) { |
| | | return; |
| | | } |
| | |
| | | public static void sendMessageAll(String message) { |
| | | ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message)); |
| | | } |
| | | |
| | | /** |
| | | * 推送消息到其他客户端 |
| | | * |
| | |
| | | JSONObject jsonObject = new JSONObject(message); |
| | | ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, jsonObject.toString())); |
| | | } |
| | | |
| | | /** |
| | | * 推送消息到其他客户端 |
| | | * |
| | |
| | | String jsonMessage = JSONObject.toJSONString(message); // 确保对象转换为 JSON 字符串 |
| | | ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, jsonMessage)); |
| | | } |
| | | |
| | | /** |
| | | * 推送消息到其他客户端 |
| | | * |
| | |
| | | public static void sendMessageAll(List message) { |
| | | ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, JSON.toJSONString(message))); |
| | | } |
| | | /** |
| | | * 发送消息给userId_前缀的人 |
| | | */ |
| | | 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 -> WebSocketUtil.sendMessage(session, message)); |
| | | } |
| | | |
| | | } |