@OnMessage public void setAktionId(Long aktionId, Session session) { logger.info("Client " + session.getId() + " hat Aktion " + aktionId + " ausgewählt."); try { List<Spende> result = new LinkedList<>(); try { result = spendeListProvider.getSpendeList(aktionId); } catch (NotFoundException e) { session .getBasicRemote() .sendText("Die Aktion mit der ID: " + aktionId + " ist nicht verfügbar"); } catch (WebApplicationException e) { logger.log( Level.SEVERE, "Die Spendenliste für Aktion mit ID: " + aktionId + " konnte nicht abgerufen werden. Läuft der JBoss?", e); session.getBasicRemote().sendText("Fehler beim Abruf der initialen Spendenliste."); } session.getUserProperties().put(AKTION_ID, aktionId); for (Spende spende : result) { logger.info("Sende " + spende + " an Client " + session.getId()); session.getBasicRemote().sendObject(spende); } session.getBasicRemote().sendText("Aktion geändert zu: " + aktionId); } catch (IOException | EncodeException e) { logger.log(Level.INFO, "Keine Verbindung zu Client: " + session, e); } }
/** * @param message { type: nickname: invitationName: // receive: msg: muc: } * @param session */ @OnMessage public String onMessage(String message, Session session) { String rs = null; JSONObject object = null; String sessionID = session.getId(); object = new JSONObject(message); System.out.println("message---------" + object.toString() + "--" + session.getId()); switch ((String) object.get("type")) { case "nickname": login(object, sessionID); case "empty": // System.out.println(new // Timestamp(System.currentTimeMillis())+"--HeartBeat--"+session.getId()); break; case "create_muc": rs = createMuc(object, sessionID); break; case "invite": rs = invite(object, sessionID); break; case "msg": rs = msg(object, sessionID); break; case "receive": // 接受邀请 rs = receive(object, sessionID); break; case "broadcast": rs = broadcast(object, sessionID); break; default: System.out.println("-------Do nothing"); break; } return rs; }
@OnClose public void onClose(Session session) { System.out.println(session.getId() + "------has closed"); // sess_map.remove(session.getId()); AbstractXMPPConnection conn = conn_map.get(session.getId()); conn.disconnect(); sess_map.remove(session.getId()); conn_map.remove(session.getId()); }
public void sendData(ResponseDTO resp, String sessionID) throws IOException, Exception { for (Session session : peers) { if (sessionID.equals(session.getId())) { session.getBasicRemote().sendBinary(getZippedResponse(resp)); } } }
@OnClose public void onClose(Session session) { String id = session.getId(); String userThatleft = null; String userThatLeftRoom = null; sessionList.remove(session); for (int i = 0, size = userList.size(); i < size; i++) { if (userList.get(i)[0].equals(id)) { userThatleft = formatIfUserWasAfk(userList.get(i)[1]); userThatLeftRoom = userList.get(i)[2]; userList.remove(i); break; } } try { for (int j = 0, jsize = userList.size(); j < jsize; j++) { if (!userList.get(j)[2].equals(userThatLeftRoom)) continue; sessionList.get(j).getBasicRemote().sendText("{\"userLeft\":\"" + userThatleft + "\"}"); } } catch (Exception e) { } }
@OnMessage public void onTextMsg(String jsonStr) { Gson gson = new GsonBuilder().serializeNulls().create(); try { jsonStr = jsonStr.trim(); LOG.debug("Rcv.:" + jsonStr + " from: " + thisSession.getId()); Message clientMsg = gson.fromJson(jsonStr, Message.class); if (clientMsg.TYPE.equals("PING")) { sendPong(); } if (clientMsg.TYPE.equals("JOIN")) { joinChat(); } if (clientMsg.TYPE.equals("CHAT")) { handleChat(clientMsg); } } catch (JsonSyntaxException e) { LOG.error("@OnMessage: " + e); } }
public List<Session> getOthers(final Session session) { return sessions .entrySet() .stream() .filter(p -> !p.getKey().equals(session.getId())) .map(Map.Entry::getValue) .collect(Collectors.toList()); }
@OnClose public void onClose() { LOG.debug("@OnClose: " + thisSession.getId()); if (isHttpSessionValid) { httpSession.removeAttribute("CHAT_OPEN"); } unjoinChat(); }
@OnOpen public void onOpen(Session session) { peers.add(session); try { ResponseDTO r = new ResponseDTO(); r.setSessionID(session.getId()); session.getBasicRemote().sendText(gson.toJson(r)); log.log(Level.WARNING, "onOpen...sent session id: {0}", session.getId()); } catch (IOException ex) { log.log(Level.SEVERE, "Failed to open web socket session", ex); platformUtil.addErrorStore(ResponseDTO.ERROR_WEBSOCKET, ex.getMessage(), SOURCE); } catch (Exception ex) { log.log(Level.SEVERE, null, ex); platformUtil.addErrorStore(ResponseDTO.ERROR_WEBSOCKET, ex.getMessage(), SOURCE); } }
@OnOpen public void open(Session session) { System.out.println("Opening client Session : " + session.getId()); try { session.getBasicRemote().sendText("test"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * クライアントの切断時にコールされる * * <p>引数は前述の通り、省略可能 * * @param client 接続 * @param reason 切断理由 */ @OnClose public void onClose(Session client, CloseReason reason) { System.out.println( client.getId() + " was closed by " + reason.getCloseCode() + "[" + reason.getCloseCode().getCode() + "]"); }
/** * When a user sends a message to the server, this method will intercept the message and allow us * to react to it. For now the message is read as a String. */ @OnMessage public void onMessage(Message message, Session session) { System.out.println("Message from " + session.getId() + ": " + message); UserType userType = UserType.valueOf(getPropertyStringValue(message, "usertype").toUpperCase()); if (userType != null) { handleMessage(message, session, userType); } else { sendMessage(prepareMessage(MessageType.ERROR, "UserType not defined"), session); } }
private void activeClose(CloseReason reason) { try { if (thisSession.isOpen()) { LOG.debug("Closing connection to peer: " + thisSession.getId()); thisSession.close(reason); } } catch (IOException e) { LOG.error(e); } }
/** * When a user sends a message to the server, this method will intercept the message and allow us * to react to it. For now the message is read as a String. */ @OnMessage public void onMessage(String message, Session session) { Logger logger = LogManager.getFormatterLogger(EchoService.class); logger.info("Message from " + session.getId() + ": " + message); try { session.getBasicRemote().sendText(message); } catch (IOException ex) { ex.printStackTrace(); logger.error(ex.getMessage(), ex); } }
@OnOpen public void open(Session session) { peers.add(session); Tweet tweet = new Tweet(); tweet.setAuthor("THE SERVER"); tweet.setMessage("Welcome! We will provide you with data " + "as soon as we have it available"); List<Tweet> tweets = Arrays.asList(tweet); session.getAsyncRemote().sendText(Tweet.listToJsonArray(tweets).toString()); logger.info("opened session with id " + session.getId()); }
@OnOpen public void onOpen(final Session session) { System.out.println(" --------------------------------------------------------------------- "); System.out.println(" WsCommunicationsTyrusCloudClientChannel - Starting method onOpen"); System.out.println(" WsCommunicationsTyrusCloudClientChannel - id = " + session.getId()); System.out.println( " WsCommunicationsTyrusCloudClientChannel - url = " + session.getRequestURI()); this.clientConnection = session; }
@OnOpen public void onOpen(Session session) { try { // add new user to list of users sessionList.add(session); // send new user their session id session.getBasicRemote().sendText("{\"sessionId\":\"" + session.getId() + "\"}"); } catch (IOException e) { } }
@Test public void testSessionExpiryContainer() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener( new ApplicationListener(TesterEchoServer.Config.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); // Need access to implementation methods for configuring unit tests WsWebSocketContainer wsContainer = (WsWebSocketContainer) ContainerProvider.getWebSocketContainer(); // 5 second timeout wsContainer.setDefaultMaxSessionIdleTimeout(5000); wsContainer.setProcessPeriod(1); connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC); connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC); Session s3a = connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC); // Check all three sessions are open Set<Session> setA = s3a.getOpenSessions(); Assert.assertEquals(3, setA.size()); int count = 0; boolean isOpen = true; while (isOpen && count < 8) { count++; Thread.sleep(1000); isOpen = false; for (Session session : setA) { if (session.isOpen()) { isOpen = true; break; } } } if (isOpen) { for (Session session : setA) { if (session.isOpen()) { System.err.println("Session with ID [" + session.getId() + "] is open"); } } Assert.fail("There were open sessions"); } }
private void sendMessage(final Message serverMsg) { final Gson gson = new Gson(); try { final String jsonStr = gson.toJson(serverMsg); if (thisSession.isOpen()) { LOG.debug("Send: " + jsonStr + " to: " + thisSession.getId()); thisSession.getBasicRemote().sendText(jsonStr); } } catch (Exception e) { LOG.error(e); } }
/** * @OnOpen allows us to intercept the creation of a new session. The session class allows us to * send data to the user. In the method onOpen, we'll let the user know that the handshake was * successful. */ @OnOpen public void onOpen(Session session) { Logger logger = LogManager.getFormatterLogger(EchoService.class); logger.info(session.getId() + " has opened a connection"); logger.info("MaxBinaryMessageBufferSize %d", session.getMaxBinaryMessageBufferSize()); logger.info("MaxIdleTimeout %d", session.getMaxIdleTimeout()); logger.info("MaxTextMessageBufferSize %d", session.getMaxTextMessageBufferSize()); logger.info("Open sessions size %d", session.getOpenSessions().size()); logger.info("Protocol %s", session.getProtocolVersion()); logger.info("QueryString %s", session.getQueryString()); try { session.getBasicRemote().sendText("Connection Established"); } catch (IOException ex) { ex.printStackTrace(); logger.error(ex.getMessage(), ex); } }
/** * deprecated: 接收到客户端关闭时调用 * * <p>date 2015-03-06 * * @author sharkTang * @param session * @param closeReason */ @OnClose public void onClose(Session session, CloseReason closeReason) { try { logger_.info( "Web-socket session " + session.getId() + " sessionHashCode" + session.hashCode() + " closed, reason: " + closeReason.toString()); WebSocketManager.webSocketClientCount--; WebSocketManager.webQueryStringSet.remove(session.getQueryString()); // 关闭客户端 赋值全局session,并删除websocket对象 webSocketAction(webSocketMap, session, WebSocketConstants.REMOVE_STR, null); daPingWebsocketSession = session; webSocketMapAction(webSessionMap, session, WebSocketConstants.REMOVE_STR); } catch (Exception ex) { } }
/** * 上线 广播消息 * * @param object { nickname } * @param sessionID * @return private final static String rs = "var rs = * {type:'${0}',nickname:'${1}',mucname:'${2}',msg:'${3}'}"; */ public String broadcast(JSONObject object, String sessionID) { // Session session = sess_map.get(sessionID); // session.getBasicRemote().sendText(""); String nickname = (String) object.get("nickname"); Collection<Session> values = sess_map.values(); Iterator<Session> iterator = values.iterator(); // {type:'broadcast',nick:''} String rs1 = rs.replace("${type}", "online") .replace("${nickname}", nickname) .replace("${sessionID}", sessionID); while (iterator.hasNext()) { try { Session sess = iterator.next(); if (sess.isOpen() && !sess.getId().equals(sessionID)) { // 排除当前客户端 sess.getBasicRemote().sendText(rs1); } } catch (IOException e) { e.printStackTrace(); } } return null; }
@OnOpen public void onOpen(Session session) { LOG.debug("@OnOpen: " + session.getId()); thisSession = session; if (thisSession.getUserPrincipal() != null) { authToken = (UsernamePasswordAuthenticationToken) thisSession.getUserPrincipal(); if (authToken.isAuthenticated()) { isHttpSessionValid = true; httpSession = (HttpSession) thisSession.getUserProperties().get("httpSession"); httpSessionId = httpSession.getId(); LOG.debug("HTTP Session id: " + httpSessionId); if (httpSession.getAttribute("CHAT_OPEN") != null) { activeClose(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "ALREADY_OPEN")); } else { httpSession.setAttribute("CHAT_OPEN", true); } return; } } activeClose(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Unauthorized")); }
@OnClose public void onClose(final Session session) { LOGGER.info(String.format("closing session '%s'", session.getId())); this.session = null; }
@OnOpen public void onOpen(Session session) { LOGGER.info("connected session {}", session.getId()); session.setMaxIdleTimeout(0); this.session = session; }
/** * The user closes the connection. * * <p>Note: you can't send messages to the client from this method */ @OnClose public void onClose(Session session) { Logger logger = LogManager.getFormatterLogger(EchoService.class); logger.info("Session " + session.getId() + " has ended"); }
/** * クライアントからの接続時にコールされる。 * * <p>引数は以下が設定可能だが、メソッド内で使用しないなら省略できる。 * * @param client クライアントの接続情報 * @param config 設定情報 */ @OnOpen public void onOpen(Session client, EndpointConfig config) { System.out.println(client.getId() + " was connected."); }
/** * エラー時にコールされる。 * * @param client クライアント接続 * @param error エラー */ @OnError public void onError(Session client, Throwable error) { System.out.println(client.getId() + " was error."); error.printStackTrace(); }
@OnClose public void onClose(Session session, CloseReason closeReason) { logger.info(String.format("Session %s closed because of %s", session.getId(), closeReason)); }
@OnOpen public void onOpen(Session session) { logger.info("Connected ... " + session.getId()); }