@ServerEndpoint(value = "/datatrans/socketServer/{datatransSocket}") @Component public class SocketServer { private Session session; private static Map<String, Session> sessionPool = new ConcurrentHashMap<>(); private static Map<String, String> sessionIds = new ConcurrentHashMap<>(); public SocketServer() { } @OnOpen public void open(Session session, @PathParam(value = "datatransSocket") String datatransSocket) { this.session = session; sessionPool.put(datatransSocket, session); sessionIds.put(session.getId(), datatransSocket); System.out.println("websocket-成功"); } @OnMessage public void onMessage(String message) { System.out.println("当前发送人sessionid为" + session.getId() + "发送内容为" + message); } @OnClose public void onClose() { sessionPool.remove(sessionIds.get(session.getId())); sessionIds.remove(session.getId()); } @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } public void sendMessage( String message) { Session session = sessionPool.get("datatransSocket"); if (session == null) { return; } synchronized (session) { if (session != null) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } } } } public static int getOnlineNum() { return sessionPool.size(); } public String getOnlineTUsers() { StringBuilder TUsers = new StringBuilder(); for (String key : sessionIds.keySet()) { TUsers.append(sessionIds.get(key)).append("---------"); } return TUsers.toString(); } public void sendAll(String msg) { //for (String key : sessionIds.keySet()) { // sendMessage(sessionIds.get(key), msg); //} sendMessage(msg); } public void sendMany(String msg, String[] persons) { for (String TUserid : persons) { sendMessage(msg); } } }