Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating SockJS server with Java

I'm very new with Vert.x so excuse my newbness.

I was able to create a very simply SockJS server with Vert.x however I can't figure out how to register events/callbacks/handlers when connections are open or closed.

With JSR-356, it's drop dead simple to handle open/close connection events:

@OnOpen 
public void onOpen(Session userSession) {    
   // Do whatever you need 
}

@OnClose
public void onClose(Session userSession) {    
   // Do whatever you need
}

Using the SockJS support in Spring Framework 4.0 M1+, it's almost the same as JSR-356:

public class MySockJsServer extends TextWebSocketHandlerAdapter {   
   @Override    
   public void afterConnectionEstablished(WebSocketSession session) throws Exception {
      // Do whatever you need
   }

   @Override    
   public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
      // Do whatever you need    
   } 
}

For some reason I couldn't figure out how to do something so conceptually simple in Vert.x. I though Vert.x was simple ?!!

If anyone can point me in the right direction, please help.

I played around with EventBus and EventBus hooks but it didn't work. Perhaps that's the wrong approach anyhow.

I'm using Vert.x version 2.0.1

TIA

like image 814
Steven McCarthy Avatar asked Mar 01 '26 22:03

Steven McCarthy


1 Answers

This is the answer:

  HttpServer httpServer = vertx.createHttpServer();

  // Create HTTP server
  httpServer = httpServer.requestHandler(new Handler<HttpServerRequest>() {
     @Override
     public void handle(HttpServerRequest req) {
        req.response().sendFile("web/" + req.path());
     }
  });

  // Create SockJS Server
  SockJSServer sockJSServer = vertx.createSockJSServer(httpServer);

  sockJSServer = sockJSServer.installApp(new JsonObject().putString("prefix", "/test"), new Handler<SockJSSocket>() {

     public void handle(final SockJSSocket sock) {
        System.out.println("New session detected!");

        // Message handler
        sock.dataHandler(new Handler<Buffer>() {
           public void handle(Buffer buffer) {
              System.out.println("In dataHandler");
           }
        });

        // Session end handler
        sock.endHandler(new Handler<Void>() {
           @Override
           public void handle(Void arg) {
              System.out.println("In endHandler");
           }
        });
     }
  });

  httpServer.listen(8080);
like image 57
Steven McCarthy Avatar answered Mar 03 '26 10:03

Steven McCarthy