Advertisement
Guest User

Jetty websocket

a guest
Jul 3rd, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. import java.lang.String;
  2. import java.util.Set;
  3. import java.util.concurrent.CopyOnWriteArraySet;
  4.  
  5. import javax.servlet.http.HttpServletRequest;
  6.  
  7. import org.apache.wink.json4j.JSONObject;
  8. import org.eclipse.jetty.websocket.WebSocket;
  9. import org.eclipse.jetty.websocket.WebSocketHandler;
  10.  
  11.  
  12. public class AlarmWebSocketHandler extends WebSocketHandler {
  13.  
  14.     public final Set<AlarmWebSocket> webSockets = new CopyOnWriteArraySet<AlarmWebSocket>();
  15.     private String data;
  16.  
  17.     public AlarmWebSocketHandler() {
  18.     }
  19.  
  20.     public WebSocket doWebSocketConnect(HttpServletRequest request,
  21.             String protocol) {
  22.         return new AlarmWebSocket();
  23.  
  24.     }
  25.  
  26.     public class AlarmWebSocket implements WebSocket.OnTextMessage {
  27.  
  28.         public Connection connection;
  29.  
  30.         public void onOpen(Connection connection) {
  31.             // Client (Browser) WebSockets has opened a connection.
  32.             // 1) Store the opened connection
  33.             this.connection = connection;
  34.             // 2) Add ChatWebSocket in the global list of ChatWebSocket
  35.             // instances
  36.             // instance.
  37.             webSockets.add(this);
  38.         }
  39.  
  40.  
  41.         public void onMessage(String jsonRequest) {
  42.             // Loop for each instance of ChatWebSocket to send message server to each client WebSockets.
  43.             try {
  44.                 for (AlarmWebSocket webSocket : webSockets) {
  45.             JSONObject response2 = DoSomethingWithJsonObj(jsonRequest);              
  46.                     if(response2!=null) {webSocket.connection.sendMessage(response2.toString());}                
  47.                         }
  48.             } catch (Exception x) {
  49.                 x.printStackTrace();
  50.                 // Error was detected, close the ChatWebSocket client side
  51.                 //this.connection.disconnect();
  52.             }
  53.  
  54.         }
  55.  
  56.         public void onClose(int closeCode, String message) {
  57.             // Remove ChatWebSocket in the global list of ChatWebSocket
  58.             // instance.
  59.             webSockets.remove(this);
  60.         }
  61.     }
  62. }
  63.  
  64. //This is an elaborated version of a method introduced in
  65. //http://jansipke.nl/websocket-tutorial-with-java-server-jetty-and-javascript-client/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement