我使用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实例?有办法解决这个问题吗?
答案 0 :(得分:2)
您可以将设置代码放在加载页面后调用的方法中。在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
};
}