How to Create a Stomp-Driven Application in JavaScript Using Apache ActiveMQ as a Message Broker
Kaazing Gateway 8.12 (Battlestar) Release
Technologies used: HTML, JavaScript, Stomp, Kaazing Gateway, and Apache ActiveMQ
February 2009
Contents
Introduction
There are several innovations within the HTML 5 specification that will forever change the direction of the Web. Two of these innovations in particular--Web sockets and Server-sent events--revolutionize the way Web applications are going to be architected, developed, and deployed. Until recently, bi‑directional browser communication has been an elusive goal of the Web community. However, with updates to the HTML 5 specification, developers can now use a full-duplex communications channel that operates over a single socket.
HTML 5's WebSocket interface enables communication from the browser to any TCP-based back-end service (for example, JMS, JMX, IMAP, Jabber, and so on). For example, it is now possible to avoid convoluted architectures by simply channeling certain protocols to the browser over HTTP and Web applications can now be deployed without the need for a traditional Web application server.
Kaazing Gateway delivers a WebSocket server that enables full-duplex communication from the browser to any TCP-based back-end service. Kaazing Gateway is the first solution that understands the WebSocket protocol and provides support for all major enterprise protocols (for example, Stomp, JMS, IMAP, JDBC, Jabber, and so on).
Kaazing Gateway eliminates the need for using convoluted server- and client-side architectures to map server-side protocols to the browser over HTTP. Web developers can use the browser’s native JavaScript support and code directly against the back-end services without the need for custom Servlets or server-side programming. Before getting started, let's discuss the Stomp and Apache ActiveMQ technologies in a little bit more detail.
Overview of Stomp
Stomp (Streaming Text Oriented Messaging Protocol) is a simple, yet effective protocol. It provides an interoperable wire format that allows Stomp clients to communicate with almost every available message broker. An example of a message broker that provides built-in support for Stomp is Apache ActiveMQ. The Stomp protocol offers the following commands:
- ABORT
- ACK
- BEGIN
- COMMIT
- CONNECT
- DISCONNECT
- SEND
- SUBSCRIBE
- UNSUBSCRIBE
In this tutorial you will be using Apache ActiveMQ as the messaging system and Stomp as the communication protocol. Refer to the Stomp Protocol Specification for more information about Stomp and the Stomp commands.
One important Stomp concept--the frame--deserves a little bit more explanation. A frame encapsulates the message payload. The following is an example of a Stomp CONNECT frame, which is used by the client to establish a connection to a back-end system:
CONNECT\n
login: <username>\n
passcode:<passcode>\n
\n
^@
As shown in the example, the frame starts with a Stomp command (CONNECT, in this case), followed by a newline character. Next are the headers in <key>:<value> pairs followed by newline characters. A blank line indicates the end of the headers and the beginning of the message body and the null character indicates the end of the frame.
Overview of Apache ActiveMQ
Apache ActiveMQ is an open source message broker and JMS provider developed, distributed, and licensed by the Apache Foundation. Apache ActiveMQ provides a publish-subscribe model based on the JMS (Java Message Service) specification. It is a highly viable, light-weight solution for both queue-based peer-to-peer messaging and topic-based publish-subscribe communication. Apache ActiveMQ comes with built-in support for the Stomp protocol that is used in this tutorial. Refer to http://activemq.apache.org/ for more information about Apache ActiveMQ.
Note: For this tutorial, It is also possible to use another Stomp-compliant server, such as RabbitMQ with the rabbitmq-stomp adapter (see http://www.rabbitmq.com). By default, the Kaazing Gateway Server is configured to connect to the Stomp-compliant server on port 61613. You can configure the Stomp proxy's connect URL in the file $KAAZING_HOME/conf/gateway-config.xml.Creating a Stomp-Driven Application in JavaScript
Before getting started, let's take a look at what you are trying to build. This Web application contains the following sections:
- Connect and disconnect
- Subscribe and unsubscribe
- Begin, commit, and abort a transaction
- Message window
The following figure shows the completed Stomp-driven Web application.

Setting Up the Development Environment
Before you start building the Stomp-driven application, you must download, install, and run the Kaazing Gateway demo bundle as described in the Getting Started Guide. You will also need your favorite IDE.
Starter files are located in the $KAAZING_HOME/web/tutorials/stomp-javascript directory of the Kaazing Gateway demo bundle. These files provide a starting point to avoid having to build everything from scratch.
Creating the Stomp-Driven Application
- Navigate to $KAAZING_HOME/web/tutorials/stomp-javascript/
- Open the index.html file in your preferred IDE. As shown in the following figure, the completed Stomp-driven Web application.2, the index file is a simple HTML file. It contains a few TODO sections in the <HEAD> section of the page. This is where you will be adding extra code.
The HTML code is complete and it includes a few forms with buttons and input fields. The input fields and buttons have IDs to simplify their configuration.
- Now that you have familiarized yourself with the index.html file, you can start adding the missing pieces. First, let's add ByteSocket.js, the JavaScript library that allows us to open a socket and fully leverage bi-directional binary communication for all browsers. The ByteSocket.js library will auto-detect any native browser support for WebSocket and Server-sent events (SSE). If the browser does not support WebSocket and SSE the library will automatically fall back to Kaazing's client-side emulation of the standard.
Replace:
<script src="TODO1"></script>
With:
<script src="/html5/ByteSocket.js"></script>
- Next, you must add support for the Stomp protocol. This is an API-specific JavaScript implementation of the Stomp protocol provided by the Kaazing Gateway.
Replace:
<script src="TODO2"></script>
With:
<script src="/protocol/StompClient.js"></script>
- Next, you must create a setup() JavaScript function that is called when the page is loaded. This function will first get the element console and then define a log() function that takes a message as an argument. When the log()function is invoked, the message will be appended to the message console element at the bottom of the page.
Replace:
<script>TODO3</script>
With:
<script>
function setup() {
// detect explicit host:port authority
var authority = location.host;
if (location.search) {
authority = location.search.slice(1) + "." + authority;
}
else {
var parts = authority.split(':');
var ports = { http:'80', https:'443' };
authority = parts[0] + ':' + (parseInt(parts[1] || ports[location.protocol]) + 1);
}
var console = document.getElementById("console")
var log = function(message) {
var pre = document.createElement("pre");
pre.innerHTML = message;
console.insertBefore(pre, console.firstChild);
}
Note: You will add the </script> tag to close the script block later. - Next, you must add some variables representing the buttons and input fields in the page. Add the following code at the end of the script block that you added in the previous step.
//Default location of Kaazing Gateway
var url = document.getElementById("url");
//Connection form
var username = document.getElementById("username");
var password = document.getElementById("password");
var connect = document.getElementById("connect");
var disconnect = document.getElementById("disconnect");
//Subscription form
var destination = document.getElementById("destination");
var message = document.getElementById("message");
var subscribe = document.getElementById("subscribe");
var send = document.getElementById("send");
var unsubscribe = document.getElementById("unsubscribe");
//Transaction form
var transaction = document.getElementById("transaction");
var txSend = document.getElementById("txSend");
var txDestination = document.getElementById("txDestination");
var txMessage = document.getElementById("txMessage");
var begin = document.getElementById("begin");
var commit = document.getElementById("commit");
var abort = document.getElementById("abort");
- Now the fun starts! You are now ready to configure the buttons to execute Stomp commands that can be used to send and receive Stomp messages. First, you need the user to be able to connect and disconnect to a back-end system. Add the following code at the end of the script block that you modified in the previous step:
connect.onclick = function() { log("CONNECT: " + url.value + " " + username.value);
Note: The log() function writes the user's message to the console at the bottom of the page.
stomp.connect(url.value, {username:username.value,
password:password.value}); }
disconnect.onclick = function() { log("DISCONNECT");
stomp.disconnect(); }
- Next, you must add functionality to subscribe, send and unsubscribe to messages. Add the following code at the end of the script block that you modified in the previous step:
subscribe.onclick = function() { log("SUBSCRIBE: " + destination.value);
stomp.subscribe(destination.value);
}
send.onclick = function() { log("SEND: " + message.value + " "
+ destination.value);
stomp.send(message.value, destination.value);
}
unsubscribe.onclick = function() { log("UNSUBSCRIBE: " + destination.value);
stomp.unsubscribe(destination.value);
}
- Next, you must enable Stomp transactions. This allows the user to begin a transaction, send messages to this transaction, and commit these messages to the message queue which sends them to everybody that is subscribed to the specified destination. Add the following code at the end of the script block that you modified in the previous step:
begin.onclick = function() { log("BEGIN: " + transaction.value);
stomp.begin(transaction.value);
}
txSend.onclick = function() { log("SEND: " + txMessage.value + " "
+ txDestination.value + " " + transaction.value);
stomp.send(txMessage.value, txDestination.value,
transaction.value);
}
commit.onclick = function() { log("COMMIT: " + transaction.value);
stomp.commit(transaction.value);
}
abort.onclick = function() { log("ABORT: " + transaction.value);
stomp.abort(transaction.value);
}
- Next, you must setup a call back function so that the user can receive information from other users. By creating a new instance of the StompClient() the user will allow other users to communicate directly with our Stomp-compliant server. Add the following code at the end of the script block that you modified in the previous step:
var stomp = new StompClient();
//When user connects
stomp.onopen = function(headers) { log("CONNECTED: " + headers["session"]); }
- Additionally you can add callback functions for onreceipt, onerror, onclosed:
//Server acknowledges message
stomp.onreceipt = function(headers) { log("RECEIPT: " + headers["receipt- id"]); }
//An error occured
stomp.onerror = function(headers, body) { stompKey.purge(); log("ERROR: " + body) }
//User disconnects
stomp.onclosed = function(headers) { log("DISCONNECTED") } - Next, you must add a some code to detect the location and port of your Kaazing Gateway instance. These values can then be used in the Location field.
// Default the location
url.value = location.protocol.replace("http", "ws") + "//" + authority + "/activemq";
- Next, close the script block by adding the following code:
</script>
- Finally, to configure the JavaScript Stomp application, you must initiate the setup() function after the document has finished loading.
Replace:
<body TODO4>
With:
<body onLoad="setup()">
Congratulations! You just finished building your first JavaScript Stomp application.
Starting the Kaazing Gateway Server and Apache ActiveMQ
Before you can test the Stomp application you will have to get the runtime environment up and running. Refer to the Getting Started Guide for more information on how to install and run the Kaazing Gateway Server and Apache ActiveMQ.
Running the JavaScript Stomp Client
To test your new Stomp application you now just have to point your browser to http://[localhost:port]/tutorials/stomp-javascript/index.html. For example, http://localhost:8000/documentation/simple-stomp-tutorial.html. Your application should look like the finished application shown in the following figure.

As you try out the application,. you will see log messages in the message console in the lower-right corner of the Stomp application.
