/** 给特定的在线用户发送消息 */ public void sendMessageToUsers(ArrayList<Long> userIdList, TextMessage message) { if (userIdList == null) { return; } int listSize = userIdList.size(); if (listSize == 0) { return; } int i = 0; for (WebSocketSession user : users) { try { if (user.getAttributes().get("USER_ID") != null) { if (user.isOpen() && userIdList.contains(user.getAttributes().get("USER_ID"))) { user.sendMessage(message); i++; if (listSize == i) { break; } } } } catch (IOException e) { e.printStackTrace(); } } }
/** 连接成功 */ @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { // TODO Auto-generated method stub System.out.println(session); Map<String, String> select = new HashMap<String, String>(); String userId = (String) session.getAttributes().get("userId"); String userPwd = (String) session.getAttributes().get("userPwd"); select.put("userId", userId); select.put("userPwd", userPwd); String result = webSocketService.getNewMessage(select); session.sendMessage(new TextMessage(result.toString())); WebSocketCache.putMemberSession(select.get("userId"), session); }
@Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { Object cookies = session.getAttributes().get(HttpHeaders.COOKIE); log.info("cookies: {}; message: {}", cookies, message); session.sendMessage(message); }
/** 建立连接后 */ public void afterConnectionEstablished(WebSocketSession session) throws Exception { Long uid = (Long) session.getAttributes().get("uid"); if (userSocketSessionMap.get(uid) == null) { userSocketSessionMap.put(uid, session); } }
public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("ConnectionEstablished"); users.add(session); System.out.println( "当前总在线用户数:" + users.size() + ",当前用户ID:" + session.getAttributes().get("USER_ID")); }