@Component
@ServerEndpoint("/websocket/{userName}")
// 此注解相当于设置访问URL
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
private static Map<String, Session> sessionPool = new HashMap<String, Session>();
private final static Logger logger = LoggerFactory.getLogger(LoginIntercept.class);
@OnOpen
public void onOpen(Session session, @PathParam(value = "userName") String userName) {
this.session = session;
webSockets.add(this);
if (sessionPool.containsKey(userName)) {
sessionPool.put(userName + String.valueOf(session.getId()), session);
} else {
sessionPool.put(userName, session);
}
logger.info("【websocket消息】有新的连接,总数为:" + webSockets.size());
}
@OnClose
public void onClose() {
webSockets.remove(this);
logger.info("【websocket消息】连接断开,总数为:" + webSockets.size());
}
@OnMessage
public void onMessage(String message) {
logger.info("【websocket消息】收到客户端消息:" + message);
}
/**
* 功能描述: 此为广播消息
*
* @param: [message] (消息)
* @return: void ()
*/
public void sendAllMessage(String message) {
for (WebSocket webSocket : webSockets) {
logger.info("【websocket消息】广播消息:" + message);
try {
if (webSocket.session.isOpen()) {
webSocket.session.getAsyncRemote().sendText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 功能描述:此为单点消息 (发送文本) 现在可以发送给多客户端
*
* @param: [userName, message] (接收人,发送消息)
* @return: void ()
*/
public void sendTextMessage(String userName, String message) {
// 遍历sessionPool
for (String key : sessionPool.keySet()) {
// 存在当前用户
if (key.toString().indexOf(userName) != -1) {
Session session = sessionPool.get(key);
if (session != null && session.isOpen()) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
/**
* 功能描述: 此为单点消息 (发送文本) 现在可以发送给多客户端
*
* @param: [userName, message] (接收人,发送消息)
* @return: void ()
*/
public void sendObjMessage(String userName, Object message) {
// 遍历sessionPool
for (String key : sessionPool.keySet()) {
// 存在当前用户
if (key.toString().indexOf(userName) != -1) {
Session session = sessionPool.get(key);
if (session != null && session.isOpen()) {
try {
session.getAsyncRemote().sendObject(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}