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:

  1. vertx.eventBus().<String>consumer("app.markdown", msg -> {
  2. String html = Processor.process(msg.body());
  3. msg.reply(html);
  4. });

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:

  1. eb.send("app.markdown", text, function (err, reply) { (1)
  2. if (err === null) {
  3. $scope.$apply(function () { (2)
  4. $scope.updateRendering(reply.body); (3)
  5. });
  6. } else {
  7. console.warn("Error rendering Markdown content: " + JSON.stringify(err));
  8. }
  9. });
  1. The reply handler is a function taking two parameters: an error (if any) and the reply object. The reply object content is nested inside the body property.

  2. Since the event bus client is not managed by AngularJS, $scope.$apply wraps the callback to perform proper scope life-cycle.

  3. As we did when working with $http, we invoke updateRendering 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.