package com.shlanbao.tzsc.pms.websocket; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * */ public class WebSocketSessionUtils { private static WebSocketSessionUtils instance = new WebSocketSessionUtils(); private WebSocketSessionUtils() { } public static WebSocketSessionUtils getInstance() { return instance; } private Map clients = new ConcurrentHashMap(); /** *

记录一个连接

* * @param userId * @param webSocketSession */ public void add(String userId, WebSocketSession webSocketSession) { if (userId == null||webSocketSession==null){ System.err.println("websocket:用户名或session为空,无法建立正常连接"); } if (clients.containsKey(userId)) { clients.remove(userId); } clients.put(userId, webSocketSession); } /** *

通过id获取连接

* * @param userId * @return */ public WebSocketSession get(String userId) { return clients.get(userId); } /** *

移除连接

* * @param userId */ public void remove(String userId) { if (userId == null) return; clients.remove(userId); } public int size() { return clients.size(); } public void sendMessageToTarget(String userId, TextMessage message) { if (userId == null) return; WebSocketSession webSocketSession = clients.get(userId); sendMessage(message, webSocketSession); } private void sendMessage(TextMessage message, WebSocketSession webSocketSession) { if (webSocketSession != null) { if (webSocketSession.isOpen()) { try { webSocketSession.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } } public void sendMessageToAllTarget(TextMessage message) { Iterator iterator = clients.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry enter = (Map.Entry) iterator.next(); WebSocketSession ws = clients.get(enter.getKey()); sendMessage(message, ws); } } public Map getClients() { return clients; } }