Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.String;
- import java.util.Set;
- import java.util.concurrent.CopyOnWriteArraySet;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.wink.json4j.JSONObject;
- import org.eclipse.jetty.websocket.WebSocket;
- import org.eclipse.jetty.websocket.WebSocketHandler;
- public class AlarmWebSocketHandler extends WebSocketHandler {
- public final Set<AlarmWebSocket> webSockets = new CopyOnWriteArraySet<AlarmWebSocket>();
- private String data;
- public AlarmWebSocketHandler() {
- }
- public WebSocket doWebSocketConnect(HttpServletRequest request,
- String protocol) {
- return new AlarmWebSocket();
- }
- public class AlarmWebSocket implements WebSocket.OnTextMessage {
- public Connection connection;
- public void onOpen(Connection connection) {
- // Client (Browser) WebSockets has opened a connection.
- // 1) Store the opened connection
- this.connection = connection;
- // 2) Add ChatWebSocket in the global list of ChatWebSocket
- // instances
- // instance.
- webSockets.add(this);
- }
- public void onMessage(String jsonRequest) {
- // Loop for each instance of ChatWebSocket to send message server to each client WebSockets.
- try {
- for (AlarmWebSocket webSocket : webSockets) {
- JSONObject response2 = DoSomethingWithJsonObj(jsonRequest);
- if(response2!=null) {webSocket.connection.sendMessage(response2.toString());}
- }
- } catch (Exception x) {
- x.printStackTrace();
- // Error was detected, close the ChatWebSocket client side
- //this.connection.disconnect();
- }
- }
- public void onClose(int closeCode, String message) {
- // Remove ChatWebSocket in the global list of ChatWebSocket
- // instance.
- webSockets.remove(this);
- }
- }
- }
- //This is an elaborated version of a method introduced in
- //http://jansipke.nl/websocket-tutorial-with-java-server-jetty-and-javascript-client/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement