private String[] buildUserList(final boolean includeThis) { List<String> userList = new ArrayList<>(); LOG.debug("buildUserList(): " + thisSession.getOpenSessions().size()); for (Session session : thisSession.getOpenSessions()) { if (!includeThis && thisSession.equals(session)) { continue; } String userName = (String) session.getUserProperties().get("USER"); String userColor = (String) session.getUserProperties().get("COLOR"); userList.add(userColor + "*" + userName); } return (userList.size() == 0) ? null : userList.toArray(new String[userList.size()]); }
private void broadcastMessage(final Message serverMsg, final boolean includeThis) { final Gson gson = new Gson(); try { final String jsonStr = gson.toJson(serverMsg); for (Session session : thisSession.getOpenSessions()) { if (!includeThis && thisSession.equals(session)) { continue; } session.getAsyncRemote().sendText(jsonStr); } } catch (Exception e) { LOG.error(e); } }
/** * 接受客户端的消息,并把消息发送给连接的会 * * @param message 客户端发来的消息 * * @param session 客户端的会话 */ @OnMessage public void getMessage(String message, Session session) { for (Session openSession : session.getOpenSessions()) { /// System.out.println(message); System.out.println(message.split(":")[0]); // 利用键主键的方式获取到消息体为昵称:内容 // message=message.split(":")[0]+ DATE_FORMAT.format(new // Date())+"</br>"+message.split(":")[1]; Map result = new HashMap<String, Object>(); result.put("nickName", message.split(":")[0]); result.put("time", DATE_FORMAT.format(new Date())); result.put("message", message.split(":")[1]); messageList.add(result); if (!openSession.equals(session)) { openSession.getAsyncRemote().sendText(JsonKit.toJson(result, 2)); } } }