A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 2

August 10, 2012

In Part 1, we looked at the completed application, which we’ll start building here. Before we get started with actual development, let’s take a look at the starting application. Open a new browser tab or window with the starting application in JSFiddle. The starting app is as simple as it gets. First, take a look at the HTML code, then read the explanations below the code snippet.

<body onload="doConnect()">

<div id="logMsgs"></div>


Note: Application requires references to Kaazing WebSocket client libraries that ensure that communication between any Web browser and the WebSocket server is seamless, even if the browser doesn’t natively support the WebSocket API and protocol. Typically, <head> section of the application would include the following lines:

&lt;script src="//cdn.kaazing.com/releases/enterprise.javascript.client/4.1.0/WebSocket.js"&gt;&lt;/script&gt;
&lt;script src="//cdn.kaazing.com/releases/enterprise.javascript.client/4.1.0/JmsClient.js"&gt;&lt;/script&gt;

However, JSFiddle’s applications usually do not have <head> section; instead, references to the scripts are added using “External References” feature.

Line 01: Invokes the doConnect() function after the contents of the page is loaded.

Line 02: Defines a div tag that will contain the log messages.
At the moment, we just have a completely empty HTML page, so there’s nothing exciting to see yet. Let’s move on to the JavaScript code.

While walking through the JavaScript code, we’ll see the power of messaging. One of the key differentiators that sets the Kaazing WebSocket Gateway apart from other WebSocket servers is its extensive support for rich business protocols and messaging APIs on top of the WebSocket standard, including XMPP, JMS, and AMQP.

This tutorial focuses on the most widely used messaging API: Java Message Service (JMS). JMS is a messaging standard that allows the loose coupling of applications by creating, sending, receiving, and reading messages.

The Kaazing JMS offering extends the reach of enterprise messaging applications to the Web by providing JMS APIs in various client technologies, including Java, JavaScript, Microsoft .NET/Silverlight, as well as Flash/Flex.
In this tutorial, we focus on the JavaScript JMS APIs and how you can use JMS in modern HTML5 applications. The following code shows a simple example of a JavaScript application that uses Kaazing’s JMS APIs. Take a look at the code, then the explanations below the code snippet.

// Variables you can change
var WEBSOCKET_URL = "wss://demos.kaazing.com/jms";
var TOPIC_NAME = "/topic/myTopic";
var IN_DEBUG_MODE = true;
var DEBUG_TO_SCREEN = true;

// WebSocket and JMS variables
var connection;
var session;
var wsUrl;

// Variable for log messages
var screenMsg = "";

// JSFiddle-specific variables
var runningOnJSFiddle = (window.location.hostname === "fiddle.jshell.net");

// Used for development and debugging. All logging can be turned
// off by modifying this function.
var consoleLog = function(text) {
    if (IN_DEBUG_MODE) {
       if (runningOnJSFiddle || DEBUG_TO_SCREEN) {
           // Logging to the screen
           screenMsg = screenMsg + text + "
       } else {
        // Logging to the browser console

var handleException = function(e) {
 consoleLog("EXCEPTION: " + e);

// Connecting...
var doConnect = function() {
    // Connect to JMS, create a session and start it.
    var jmsConnectionFactory = new JmsConnectionFactory(WEBSOCKET_URL);
    try {
        var connectionFuture = jmsConnectionFactory.createConnection('', '', function() {
            if (!connectionFuture.exception) {
               try {
                   connection = connectionFuture.getValue();

                   consoleLog("Connected to " + WEBSOCKET_URL);
                   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

                   connection.start(function() {
                        // Put any callback logic here.
                        consoleLog("JMS session created");
             } catch (e) {
         } else {
 } catch (e) {

At the top of this code snippet, you can see variables that you can change.
Line 03: WEBSOCKET_URL points to the WebSocket server, which in our case runs on tutorial.kaazing.com. JMS, being a messaging API, follows the publish/subscribe pattern.

Line 04: A topic in JMS is a distribution mechanism for publishing messages that are delivered to multiple subscribers. Our topic is called /topic/myTopic. You can, and probably should change the name of the topic to your liking to ensure nobody else is interfering with your experimentation. For example:

var TOPIC_NAME = "/topic/PeterTopic"; 

Lines 05-06: The IN_DEBUG_MODE and DEBUG_TO_SCREEN variables give you simple ways to control debugging. By default, debugging is enabled and is directed to the screen.

Line 16: The screenMsg variable holds the log messages. Note: When this variable grows big, the performance of the application may degrade significantly. If you’re seeing increased latency, disabling logging of the application often helps.

Lines 20: Determines whether the app is running outside of the context of JSFiddle.

Line 25: The consoleLog() function is used for logging. It honors the preferences set through the logging variables, specified in lines 05-06.

Line 44: The doConnect() function is in charge of establishing the WebSocket connection.

Line 47: Next, we create a JmsConnectionFactory, allowing us to create a connection with a JMS provider via a WebSocket connection.

Line 49: Then, we create a connection, where ConnectionFuture handles the returned result.

Line 51: Finally, we create a session. Optionally, you can use sessions to handle transactions. This tutorial doesn’t use transactions. When you run this code, the Result pane in the bottom right displays the following log messages:

Connected to wss://demos.kaazing.com/jms JMS session created 

In Part 3, we will evolve our application.
The online HTML Tidy code editor tool helps you organize your code easily in your browser without download or registration. It is absolutely free!