2013-10-06 47 views
3

我對Vert.x非常新,所以原諒我的新手。用Java創建SockJS服務器

我能夠用Vert.x創建一個非常簡單的SockJS服務器,但我無法弄清楚在連接打開或關閉時如何註冊事件/回調/處理程序。

隨着JSR-356,它的下降死的簡單處理打開/關閉連接事件:

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

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

使用SockJS支持Spring框架4.0 M1 +,這是幾乎相同的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  
    } 
} 

出於某種原因,我無法弄清楚如何在Vert.x中做到如此簡單的操作。我雖然Vert.x很簡單?

如果有人能指出我的方向正確,請幫忙。

我用EventBus和EventBus鉤子玩過,但沒有奏效。無論如何,這也許是錯誤的方法。

我使用Vert.x 2.0.1版

TIA

+0

這是答案: sockJSServer = sockJSServer.installApp(新的JSONObject ().putString(「prefix」,「/ test」),new Handler (){public void handle(final SockJSSocket sock){ \t \t System。 out.println(「檢測到新的會話!」); \t \t //會話結束處理 \t \t sock.endHandler(新處理器(){ \t \t @覆蓋 \t \t公共無效手柄(虛空ARG){ \t \t \t的System.out.println(「在endHandler「); \t \t} \t \t}); \t} }); httpServer.listen(8080); –

回答

5

這就是答案:

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);