package com.ruoyi.system.api.util; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.websocket.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * websocket 客户端用户集 * * @author ruoyi */ public class WebSocketUsers { private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUsers.class); private static Map USERS = new ConcurrentHashMap<>(); private static Map USER_TYPES = new ConcurrentHashMap<>(); public static void put(String key, Session session, Integer clientType) { USERS.put(key, session); USER_TYPES.put(key, clientType); } public static boolean remove(Session session) { String key = null; boolean flag = USERS.containsValue(session); if (flag) { Set> entries = USERS.entrySet(); for (Map.Entry entry : entries) { Session value = entry.getValue(); if (value.equals(session)) { key = entry.getKey(); break; } } } else { return true; } return remove(key); } public static boolean remove(String key) { LOGGER.info("\n 正在移出用户 - {}", key); Session remove = USERS.remove(key); USER_TYPES.remove(key); if (remove != null) { boolean containsValue = USERS.containsValue(remove); LOGGER.info("\n 移出结果 - {}", containsValue ? "失败" : "成功"); return containsValue; } else { return true; } } public static Map getUsers() { return USERS; } public static Integer getUserType(String key) { return USER_TYPES.get(key); } public static void sendMessageToUsersByText(String message) { Collection values = USERS.values(); for (Session value : values) { sendMessageToUserByText(value, message); } } public static void sendMessageToUserByText(Session session, String message) { if (session != null) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { LOGGER.error("\n[发送消息异常]", e); } } else { LOGGER.info("\n[你已离线]"); } } public static void sendMessageToUsersByType(Integer clientType, String message) { for (Map.Entry entry : USERS.entrySet()) { String key = entry.getKey(); Session session = entry.getValue(); if (clientType.equals(USER_TYPES.get(key))) { sendMessageToUserByText(session, message); } } } }