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

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.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Kaazing WebSocket Tutorial - JMS</title>
        <script src="http://demo.kaazing.com/lib/client/javascript/StompJms.js" type="text/javascript" language="javascript"></script>
    </head>
    <body onload="doConnect()">
        <div id="logMsgs"></div>
    </body>
</html>

Line 05: References the 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.
Line 07: Invokes the doConnect() function after the contents of the page is loaded.
Line 08: 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 MY_WEBSOCKET_URL = "ws://tutorial.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;

// JSFiddle-specific variables
//
var runningOnJSFiddle = (window.location.hostname === "fiddle.jshell.net");
var WEBSOCKET_URL = (runningOnJSFiddle ? MY_WEBSOCKET_URL : "ws://" + window.location.hostname + ":" + window.location.port + "/jms");

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

// 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 + "
";
            $("#logMsgs").html(screenMsg);
        } else {
            // Logging to the browser console
            console.log(text);
        }
    }
};

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

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

                    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) {
                    handleException(e);
                }
            } else {
                handleException(connectionFuture.exception);
            }
        });
    } catch (e) {
        handleException(e);
    }
};
​

At the top of this code snippet, you can see variables that you can change.

Line 03: MY_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.

Lines 16-17: If the app is running outside of the context of JSFiddle, the WebSocket URL is constructed dynamically, pointing back to the same server where the HTML page was downloaded from.

Line 21: 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.

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

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

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

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

Line 57: 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 ws://tutorial.kaazing.com/jms
JMS session created

In Part 3, we will evolve our application.

This entry was posted in html5, Kaazing, WebSocket and tagged , . Bookmark the permalink.

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

  1. Pingback: A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 1 | The Zinger

  2. Pingback: A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 3 | The Zinger

  3. Pingback: A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 4 | The Zinger

  4. Pingback: A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 5 | The Zinger

  5. Pingback: A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 6 | The Zinger

  6. Pingback: A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 7 | The Zinger

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s