Reputation: 1715
I build up with Vertx SockJs an Eventbus Bridge.
This is the code for my 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!");
});
}
This is the code of 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;
};
Now what Im concerned about:
After my verticle created a connection with the client, all is ok. But when Im restarting my verticle Im getting NO_HANDLER
errors, because there is likely no new instance of Eventbus? Is there a way to handle this?
Upvotes: 0
Views: 319
Reputation: 9128
You can put your setup code in a method called after the page is loaded. In the onclose
callback, cleanup all reply handlers (you will never get the server response) and call your setup method again.
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
};
}
Upvotes: 2