Search code examples
javavert.xsockjsvertx-verticle

Vertx 3 - SockJS socket opening canceled


I created a new verticle that should response for HTTP requests and SockJS bridged events. Based on this question https://stackoverflow.com/questions/41516328 and vert.x manual https://vertx.io/docs/vertx-web/java/#_sockjs I created this piece of code:

Java:

    @Override
    public void start(Future<Void> startFuture) throws Exception {
        startHttpServer(startFuture);
        startSockJSHandler();
    }

    private void startHttpServer(Future<Void> startFuture) {
        HttpServer server = vertx.createHttpServer(new HttpServerOptions());
        server.requestHandler(req -> {
            System.out.println("[" + new Date().toString() + "] Request #" + ++requestCount);
            if (req.path().contains("http")) {
                req.response().putHeader("Access-Control-Allow-Origin", "*").end("req_num: " + requestCount);
            }
        }).listen(8080, ar -> startFuture.handle(ar.mapEmpty()));
    }

    private void startSockJSHandler() {
        Router router = Router.router(vertx);
        SockJSHandlerOptions sockJSOptions = new SockJSHandlerOptions().setHeartbeatInterval(2000);
        SockJSHandler sockJSHandler = SockJSHandler.create(vertx, sockJSOptions);
        BridgeOptions bridgeOptions = new BridgeOptions();
        bridgeOptions.addInboundPermitted(new PermittedOptions().setAddressRegex(".*")).addOutboundPermitted(new PermittedOptions().setAddressRegex(".*"));
        sockJSHandler.bridge(bridgeOptions, be -> {
            System.out.println("BRIDGE EVENT: " + be.type().toString());
        });
        router.route("/eventbus/*").handler(sockJSHandler);
    }

JavaScript eventbus client:

var sock = new SockJS('http://localhost:8080/eventbus/');

sock.onopen = function() {
  console.log('open');
  sock.send('test');
};

sock.onmessage = function(e) {
  console.log('message', e.data);
  sock.close();
};

sock.onclose = function() {
  console.log('close');
};

HTTP request/response works fine, but SockJS events not. In web browser 'Network' module I see only one SockJS request (http://localhost:8080/eventbus/info). 8 seconds in 'pending' status, and after this time the status is changed to 'closed' (method onclose() is called at the end).

Did I do something wrong?


Solution

  • The HttpServer must delegate requests to the Router. Otherwise nothing happens. Usually, it is configured to delegate all requests to the Router.

    server.requestHandler(router::accept).listen(8080);
    

    See Basic Vert.x-Web concepts in the docs.