我对Vert.x很新,请原谅我的新闻.
我能够使用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
}
使用Spring Framework 4.0 M1中的SockJS支持,它与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
解决方法:
这就是答案:
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);