package com.ruoyi.system.websocket;
|
|
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<String, Session> USERS = new ConcurrentHashMap<>();
|
private static Map<String, Integer> 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<Map.Entry<String, Session>> entries = USERS.entrySet();
|
for (Map.Entry<String, Session> 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<String, Session> getUsers()
|
{
|
return USERS;
|
}
|
|
public static Integer getUserType(String key) {
|
return USER_TYPES.get(key);
|
}
|
|
public static void sendMessageToUsersByText(String message)
|
{
|
Collection<Session> 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[你已离线]");
|
}
|
}
|
|
/**
|
* 根据客户端类型发送消息
|
*
|
* @param clientType 1=会员小程序 2=拍卖师小程序
|
* @param message 发送的消息
|
*/
|
public static void sendMessageToUsersByType(Integer clientType, String message) {
|
for (Map.Entry<String, Session> entry : USERS.entrySet()) {
|
String key = entry.getKey();
|
Session session = entry.getValue();
|
if (clientType.equals(USER_TYPES.get(key))) {
|
sendMessageToUserByText(session, message);
|
}
|
}
|
}
|
}
|