SockJs Eventbus Bridge:重启 Verticle 会强制我重启 ClientHtml?

SockJs Eventbus Bridge: Restarting Verticle forces me to restart ClientHtml?

我用 Vertx SockJs 搭建了一个 Eventbus Bridge。

这是我的verticle的代码:

@Override
public void start() throws Exception {
    Router router = Router.router(vertx);

    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    BridgeOptions options = new BridgeOptions();

    options.addInboundPermitted(new PermittedOptions().setAddress("test"));
    options.addOutboundPermitted(new PermittedOptions().setAddress("test"));
    options.addInboundPermitted(new PermittedOptions().setAddress("test2"));
    options.addOutboundPermitted(new PermittedOptions().setAddress("test2"));

    sockJSHandler.bridge(options);

    router.route("/eventbus/*").handler(sockJSHandler);

    vertx.createHttpServer().requestHandler(router::accept).listen(8600);

    vertx.setTimer(5000, id -> {
        vertx.eventBus().send("test", "hallo!", async -> {
            if (async.succeeded()) {
                System.out.println("Success!");
            } else {
                System.out.println("Failure!");
                System.out.println(async.cause());
            }
        });
        System.out.println("SEND!");
    });

}

这是ClientHtml的代码:

var eb = new EventBus('http://localhost:8600/eventbus');

eb.onError=function() {
    console.log('error');
}

eb.onopen = function() {
    console.log('connected');
  // set a handler to receive a message
  eb.registerHandler('test', function(error, message) {
    console.log('received a message: ' + JSON.stringify(message));
    $( "#text" ).html(JSON.stringify(message));
  });

  eb.registerHandler('test2', function(error, message) {
        console.log('received a message: ' + JSON.stringify(message));
        console.log("Error: "+error);
        $( "#text2" ).html(JSON.stringify(message));
      });
}

eb.onclose = function() {
    console.log("disconnected");
    eb = null;
};

现在我关心的是:

我的verticle与客户端建立连接后,一切正常。但是当我重新启动我的 Verticle 时,我收到 NO_HANDLER 错误,因为可能没有新的 Eventbus 实例?有办法处理吗?

您可以将设置代码放在页面加载后调用的方法中。在 onclose 回调中,清除所有回复处理程序(您将永远不会收到服务器响应)并再次调用您的设置方法。

function setupEventBus() {
  var eb = new EventBus(window.location.protocol + "//" + window.location.host + "/eventbus");
  eb.onclose = function (e) {
    // Cleanup reply handlers
    var replyHandlers = eb.replyHandlers;
    for (var address in replyHandlers) {
      if (replyHandlers.hasOwnProperty(address)) {
        replyHandlers[address]({
          failureCode: -1,
          failureType: "DISCONNECT",
          message: "EventBus closed"
        });
      }
    }
    // Setup the EventBus object again (after some time)
    setTimeout(setupEventBus, 1000);
  };
  eb.onopen = function () {
    // Register your handlers here
  };
}