Setting up the SockJS event bus bridge
On the server
Note | SockJS is a client-side JavaScript library and protocol that provides a simple WebSocket-like interface for making connections to SockJS servers, irrespective of whether the actual browser or network will allow real WebSockets. It does this by supporting various different transports between browser and server, and choosing one at runtime according to their capabilities. |
As a first step, we need to setup the SockJSHandler
that is provided by the vertx-web
project:
SockJSHandler sockJSHandler = SockJSHandler.create(vertx); (1)
BridgeOptions bridgeOptions = new BridgeOptions()
.addInboundPermitted(new PermittedOptions().setAddress("app.markdown")) (2)
.addOutboundPermitted(new PermittedOptions().setAddress("page.saved")); (3)
sockJSHandler.bridge(bridgeOptions); (4)
router.route("/eventbus/*").handler(sockJSHandler); (5)
Create a new
SockJSHandler
for thisvertx
instance.Allow delivery of messages coming from the browser on the
app.markdown
address. We will use this address to get the server process the Markdown content as we edit a wiki page.Allow sending messages going to the browser on the
page.saved
address. We will use this address to notify browsers that a wiki page has been modified.Configure the handler to bridge SockJS traffic to the event bus.
Handle all requests under the
/eventbus
path with the SockJS handler.
Caution | For most applications you probably do not want client side JavaScript to be able to send just any message to any handler on the server side, or to all other browsers. For example:
To deal with this, a SockJS bridge will by default refuse any messages through. This is why it is up to you to tell the bridge what messages are ok for it to pass through (as an exception reply messages are always allowed to pass through). |
On the client
Now that the server is ready to accept messages, we shall configure the client.
First, the SockJS library and the Vert.x event bus JavaScript client must be loaded. The easiest way to get started is to get the files from a public content delivery network:
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.3.0/sockjs.min.js"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vertx/3.5.4/vertx-eventbus.min.js"
crossorigin="anonymous"></script>
Note | The event bus client can be downloaded beforehand and bundled with the application. It is published on Maven , npm , bower and even webjars repositories. |
Then, we create a new instance of the EventBus
Javascript object:
var eb = new EventBus(window.location.protocol + "//" + window.location.host + "/eventbus");