Sending the Markdown content over the event bus for processing
The SockJS bridge is now up and running. In order to process the Markdown content on the server side, we need to register a consumer. The consumer handles messages sent to the app.markdown
address:
vertx.eventBus().<String>consumer("app.markdown", msg -> {
String html = Processor.process(msg.body());
msg.reply(html);
});
There is nothing new here, we have already been creating event bus consumers before. Now let’s turn to what happens in the client code:
eb.send("app.markdown", text, function (err, reply) { (1)
if (err === null) {
$scope.$apply(function () { (2)
$scope.updateRendering(reply.body); (3)
});
} else {
console.warn("Error rendering Markdown content: " + JSON.stringify(err));
}
});
The reply handler is a function taking two parameters: an error (if any) and the
reply
object. Thereply
object content is nested inside thebody
property.Since the event bus client is not managed by AngularJS,
$scope.$apply
wraps the callback to perform proper scope life-cycle.As we did when working with
$http
, we invokeupdateRendering
with the HTML result.
Admittedly, the code is very similar to its HTTP endpoint equivalent. However the benefit here does not lie in the number of lines of code.
Indeed, if you communicate with the server over the event bus, the bridge transparently distributes incoming messages among registered consumers. Consequently, when Vert.x runs in cluster mode, the browser is not tied to a single server for processing (apart from the SockJS connection). What’s more the connection to the server is never closed, so with HTTP/1.1 this saves establishing a TCP connection for each request, which may be useful if you have lots of exchanges between servers and clients.