Kaazing WebSocket Gateway |
|
Creating a Stomp-Driven Application in JavaScript |
|
Technologies used: JavaScript, Stomp, Kaazing WebSocket Gateway, and Apache ActiveMQ |
This document contains the following sections:
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, and Jabber). 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 WebSocket Gateway delivers an enterprise WebSocket server that enables full-duplex communication from the browser to any TCP-based back-end service. Kaazing WebSocket Gateway is the first enterprise solution that understands the WebSocket protocol and enables direct communication with all major enterprise protocols (for example, Stomp, JMS, IMAP, JDBC, and Jabber).
Kaazing WebSocket 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.
Overview of Stomp
Streaming Text Oriented Messaging Protocol (Stomp) 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 use 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 Java Message Service (JMS) 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 Stomp 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, Kaazing Gateway 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.WebSocket and Stomp
WebSocket enables direct communication from the browser to a Stomp broker. Kaazing Gateway provides the StompClient client library, which radically simplifies the application design and 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.
Using the StompClient JavaScript client library, you can take advantage of many Stomp features, making JavaScript a first-class citizen in Stomp JMS applications. Since the implementation is layered on top of ByteSocket, which uses WebSocket--and thus the entire stack of Kaazing HTML 5 Communications client libraries--applications developed using the StompClient JavaScript library are provided with guaranteed persistence, reliability, and message-receipt acknowledgment all the way to the browser.
Creating a Stomp-Driven Application in JavaScript
Before you start, take a look at what you are trying to build. The following figure shows the completed Stomp-driven Web application. This Web application contains the following sections:
- Connect and disconnect
- Subscribe and unsubscribe
- Begin, commit, and abort a transaction
- Message window

Setting Up the Development Environment
Before you start building the Stomp-driven application, you must download, install, and run the Kaazing WebSocket Gateway demo bundle as described in Getting Started. You also need your favorite IDE.
A starter file--index.html--is located in the KAAZING_HOME/web/tutorials/stomp-javascript directory of the Kaazing WebSocket Gateway demo bundle. For your convenience, a completed example file--index-completed.html-- is also included.
Creating the Stomp-Driven Application
- Navigate to KAAZING_HOME/web/tutorials/stomp-javascript/.
- Open the index.html file in your preferred IDE. 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 add extra code. The HTML code is complete and it includes a few forms with buttons and text boxes. The text boxes and buttons have IDs to simplify their configuration.
- Once you have familiarized yourself with the index.html file, you can start adding the missing pieces. First, add a reference to the ByteSocket client library, which allows you to open a socket and fully leverage bi-directional binary communication for all browsers. The ByteSocket client library auto-detects any native browser support for WebSocket and Server-sent events (SSE). If the browser does not support WebSocket and SSE the library automatically falls back to Kaazing's client-side emulation of the standard.
Note: The StompClient client library is layered on top of ByteSocket. Although Stomp is a text-based protocol, the body of a Stomp message can contain bytes, provided a Content-Length header is specified. Therefore, WebSocket, which is text-based, cannot be used to implement a fully-compatible Stomp client, because it would break on non-text body content. Additionally, each Stomp message ends with a null byte, which can cause browsers to ignore the content of the string that follows that null byte.
Replace:
<!-- TODO1 -->
With:
<script src="/html5/ByteSocket.js"></script>
- Next, you must reference the API-specific JavaScript implementation of the Stomp protocol provided by Kaazing Gateway.
Replace:
<!-- TODO2 -->
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 defines a log() function that takes a message as an argument. When the log()function is invoked, the message is appended to the message console element at the bottom of the page.
Replace:
<!-- TODO3 -->
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]) );
}
var console = document.getElementById("console")
var log = function(message) {
var pre = document.createElement("pre");
pre.innerHTML = message;
console.insertBefore(pre, console.firstChild);
while (console.childNodes.length > 500)
{
console.removeChild(console.lastChild);
}
}
Note: You will add the </script> tag to close the script block later. - Next, you must add some variables representing the buttons and text boxes in the page. The following example shows how you can complete 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. The following example shows how you can complete the script block that you modified in the previous step:
connect.onclick = function() { log("CONNECT: " + url.value + " " +
Note: The log() function writes the user's message to the console at the bottom of the page.
username.value);
stomp.connect(url.value, {username:username.value, password:password.value});
connect.disabled = "disabled"; }
disconnect.onclick = function() { log("DISCONNECT");
stomp.disconnect();
disconnect.disabled = "disabled"; }
- Next, you must add functionality to subscribe, send and unsubscribe to messages. The following example shows how you can complete 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. The following example shows how you can complete 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 allows other users to communicate directly with our Stomp-compliant server. The following example shows how you can complete 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"]);
disconnect.disabled = null; }
- Additionally you can add callback functions for onmessage, onreceipt, onerror, and onclose:
stomp.onmessage = function(headers, body) { log("MESSAGE: " + body); }
stomp.onreceipt = function(headers) { log("RECEIPT: " + headers[
"receipt-id"]); }
stomp.onerror = function(headers, body) { log("ERROR: " + body); }
stomp.onclose = function(headers) { log("DISCONNECTED");
connect.disabled = null; disconnect.disabled = "disabled"; } - 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 text box.
// Default the location
url.value = location.protocol.replace("http", "ws") + "//" + authority +
"/activemq";
// initialize the disabled states
connect.disabled = null;
disconnect.disabled = "disabled";
- 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:
<!-- TODO4 -->
With:
<body onLoad="setup()">
Congratulations! You just finished building your first JavaScript Stomp application.
Starting Kaazing Gateway and Apache ActiveMQ
Before you can test the Stomp application you must get the runtime environment up and running. Refer to Getting Started for more information on how to install and run Kaazing Gateway 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/tutorials/stomp-javascript/index.html. Your application should look like the finished application shown earlier. As you try out the application, log messages display in the message console in the lower-right corner of the Stomp application.
Note: If you want to see two or more browsers communicate, and you are running Kaazing Gateway on your local system, you can launch two or more browser instances. For example, Internet Explorer and Firefox.