/** * Broadcast a message to all connected WebSocket clients (Simple WebSocket test) * * @param text */ protected void broadcast(String text) { // System.out.println("Broadcasting message to all connected WebSocket clients : " + text); for (WebSocket webSocket : this.getWebSockets()) { try { webSocket.send(text); } catch (Exception e) { e.printStackTrace(); webSocket.close(); } } java.util.logging.Logger.getAnonymousLogger() .log(Level.INFO, "Broadcasted message to all connected WebSocket clients: " + text); }
@Override public void close() { logger.trace( "WebSocket.close() for AtmosphereResource {}", resource() != null ? resource().uuid() : "null"); webSocket.close(); }
/** * Event handler to handle when a WebSocket connection has been closed * * @param socket * @param frame */ @Override public void onClose(WebSocket socket, DataFrame frame) { super.onClose(socket, frame); // Create a log message java.util.logging.Logger.getAnonymousLogger() .log( Level.INFO, "Time: " + new java.util.Date() + ", " + "Terminated connection with WebSocket client: " + socket.toString()); }
@Override public void onConnect(WebSocket socket) { super.onConnect(socket); // Create a log message java.util.logging.Logger.getAnonymousLogger() .log( Level.INFO, "Time: " + new java.util.Date() + ", " + "Connection established with new WebSocket client: " + socket.toString()); }
/** Called whenever the server receives a message from a client */ @Override public void onMessage(WebSocket socket, String text) { super.onMessage(socket, text); // Log the received message java.util.logging.Logger.getAnonymousLogger() .log( Level.INFO, "Time: " + new java.util.Date() + ", " + "Application received request from client " + socket.toString() + ". Msg: " + text); // Send the received message back to the client from which it originated /** * socket.send("Hello Client " + socket.toString() + ". I received the " + "following message * from you: " + text + "\n"); */ /*socket.send("<br />Hello Client " + socket.toString() + ". <br/>I received the " + "following message from you:<br />" + text);*/ // Check whether client // Create JSON object JSONParser parser = new JSONParser(); // Convert the received string to JSON JSONObject jsonObj = null; try { jsonObj = (JSONObject) parser.parse(text); // Receive the new JSON object this.msgReceiver.handleIncomingMessage(jsonObj); } catch (ParseException e) { e.printStackTrace(); } /**/ }
@Override public WebSocket write(byte[] data, int offset, int length) throws IOException { logger.trace("WebSocket.write() for {}", resource() != null ? resource().uuid() : ""); webSocket.send(Arrays.copyOfRange(data, offset, length)); return this; }
@Override public WebSocket write(String s) throws IOException { logger.trace("WebSocket.write() for {}", resource() != null ? resource().uuid() : ""); webSocket.send(s); return this; }
@Override public boolean isOpen() { return webSocket.isConnected(); }