KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

WebSocket Example

Introduction

The application in the previous does not do much but test for WebSocket browser support. Let us now create an application that actually uses the WebSocket to connect to the WebSocket server. Our application will basically connect to the server, send a simple message which the server will echo back then close the connection. The application will also show the values of the readyState and bufferedAmount attributes.

We will create two files this time, one file for JavaScript code and the other file for HTML code. This is considered a good practice compared to mixing the HTML and JavaScript code. The application will first test for WebSocket support in the users’ browser before deciding whether to display the WebSocket components or not. The flowchart shows the logical flow of the program

We will start with the HTML code first

Create a new file called websocket.html

Add the following code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Websockets support tester</title> 
        <script src="websocket_client.js"></script>
    </head>
    <body onload="javascript:init()">
        <h2>WebSocket Simple Application</h2>   

        <div id = "websocketelements">
            <div id="send">
                <a href="javascript:doSend('Experience the awesomeness of websockets')">Send Message to WebSocket Server</a>
            </div>

            <div id="close">
                <a href="javascript:onClose()">Close connection to WebSocket Server</a>
            </div>

            <hr>

            <h4>readyState and bufferedAmount attribute values log</h4>

            <div id="attributes_log"> </div>

            <hr>
        </div>

        <h4>Output Konsole</h4>

        <div id="output"></div> 
    </body>
</html>

HERE,

  • <script src="websocket_client.js"></script> links to the JavaScript file with the source code for interacting with the WebSocket server.
  • <body onload="javascript:init()"> calls the init() in the JavaScript code when the page loads.
  • <div id = "websocketelements">…</div> is the parent div object for all the WebSocket elements. This div object is a hidden element in web browsers that do not support WebSockets.
  • <div id="send">…</div> is the div object that contains the link to executing the onsend() event of the WebSocket.
  • <div id="close">…</div> is the div object that contains the link to executing the onclose() event of the WebSocket.

The rest of the source code is standard HTML code. Let’s now look at the WebSocket Constructor

WebSocket Constructor

The constructor is the method that is called when the class is initialzed. The WebSocket constructor has the following syntax

var websocket = WebSocket(url,[protocol]);

HERE,

  • url is the URL string to the WebSocket resource
  • protocol is an optional parameter, it is used to specify the protocol that the WebSocket should support.

Let’s now create the JavaScript code that will interact with the WebSocket server and manipulate the HTML elements on our web page.

Create a new file in called websocket_client.js in the same folder where you created websocket.html.

Add the following code

var wsUri = "ws://echo.websocket.org/";
var output;
var attributes_log;
var websocket;

HERE,

  • var wsUri = "ws://echo.websocket.org/"; creates a variable with the URL to the WebSocket server. Note: ws is similar to http, it is not secure. This means the messages are sent over unencrypted channel. wss is similar to https, it is secure and all communication between the client and the server is encrypted.
  • var output creates the variable that will be initialized to the Konsole div object
  • var attributes_log creates the variable that will be initialized to the Log div object
  • var websocket creates the variables that will be instantiated to the WebSocket object

Let’s now create the init() method. This method will be called when the form loads.

function init() {
    output = document.getElementById("output");
    attributes_log = document.getElementById("attributes_log");
    if (browserSupportsWebSockets() === false) {
        writeToScreen("Sorry! your web browser does not support WebSockets. Try using Google Chrome or Firefox Latest Versions");
        var element = document.getElementById("websocketelements");
        element.parentNode.removeChild(element);
        return; 
    }
    websocket = new WebSocket(wsUri);
    websocket.onopen = function() {
        writeAttributeValues('onOpen Event Fired');
        writeToScreen("CONNECTION TO " + wsUri + " has been successfully established");
    };
    websocket.onmessage = function(evt) {
        onMessage(evt)
    };
    websocket.onerror = function(evt) {
        onError(evt)
    };
}

HERE,

  • variable = document.getElementById("div_id"); assigns the respective div objects to the variables output and attributes_log using the div object id.
  • if (browserSupportsWebSockets() === false)… calls a custom function that checks whether the web browser supports WebSockets or not. If the client web browser does not support WebSockets then the div object for WebSockets is removed using JavaScript. Users using web browsers that do not support WebSockets will not be showed anything. This saves us the hell of checking for errors in web browsers that do not support WebSockets.
  • return is used to terminate the function and ignore the remaining code
  • websocket = new WebSocket(wsUri); this line instantiates the websocket variable to the WebSocket object.
  • websocket.onopen… registers the onopen() event which is called when a connection has successfully being established to the server. This event calls the writeAttributeValues and writeToScreen custom methods.
  • websocket.onmessage… registers the onmessage() event which is called when data is received from the server. This event calls the onMessage custom method.
  • websocket.onerror… registers the onerror() event which is called when an error occurs. This event calls the onError custom method.

Add the following lines to the source code file

function onMessage(evt) {
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
    writeAttributeValues('onMessage Event Fired');
}
function onError(evt) {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
    writeAttributeValues('onError Event Fired');
}
function doSend(message) {
    websocket.send(message);
    writeAttributeValues('onSend Event Fired');
    writeToScreen("SENT: " + message);
}

HERE,

  • function onClose(…)… this is a custom method for onclose method
  • function onMessage(…)… this is a custom method for onmessage event
  • function onError(…)… this is a custom method for onerror event
  • function doSend(…)… this is a custom method for onsend method

Add the following line of code to the source code file

function writeAttributeValues(prefix) {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = "INFO " + getCurrentDate() + " " + prefix + "<b> readyState: " + websocket.readyState + " bufferedAmount: " + websocket.bufferedAmount + "</b>";
    ;
    attributes_log.appendChild(pre);
}
function writeToScreen(message) {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
}
function getCurrentDate() {
    var now = new Date();
    var datetime = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
    datetime += ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();

    return datetime;
}

function browserSupportsWebSockets() {
    if ("WebSocket" in window)
    {
        return true;
    }
    else
    {
        return false;
    }
}

HERE,

writeAttributeValues() is a custom method for writing to the attributes log div object writeToScreen() is a custom method for writing to the attributes konsole div object getCurrentDate() is a custom method for retrieving the current date on the client computer. This value is used in the log files browserSupportsWebSockets() is a custom method for checking if the client web browser supports WebSockets or not.

The complete source code for websocket_client.js should be as follows

var wsUri = "ws://echo.websocket.org/";
var output;
var attributes_log;
var websocket;
function init() {
    output = document.getElementById("output");
    attributes_log = document.getElementById("attributes_log");
    if (browserSupportsWebSockets() === false) {
        writeToScreen("Sorry! your web browser does not support WebSockets. Try using Google Chrome or Firefox Latest Versions");

        var element = document.getElementById("websocketelements");
        element.parentNode.removeChild(element);

        return; //
    }

    websocket = new WebSocket(wsUri);

    websocket.onopen = function() {
        writeAttributeValues('onOpen Event Fired');
        writeToScreen("CONNECTION TO " + wsUri + " has been successfully established");
    };

    websocket.onmessage = function(evt) {
        onMessage(evt);
    };

    websocket.onerror = function(evt) {
        onError(evt);
    };
}

function onClose(evt) {
    websocket.close();
    writeAttributeValues('onClose Event Fired');
    writeToScreen("DISCONNECTED");
}

function onMessage(evt) {
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
    writeAttributeValues('onMessage Event Fired');
}

function onError(evt) {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
    writeAttributeValues('onError Event Fired');
}

function doSend(message) {
    websocket.send(message);
    writeAttributeValues('onSend Event Fired');
    writeToScreen("SENT: " + message);
}

function writeAttributeValues(prefix) {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = "INFO " + getCurrentDate() + " " + prefix + "<b> readyState: " + websocket.readyState + " bufferedAmount: " + websocket.bufferedAmount + "</b>";
    ;
    attributes_log.appendChild(pre);
}

function writeToScreen(message) {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
}

function getCurrentDate() {
    var now = new Date();
    var datetime = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
    datetime += ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();

    return datetime;
}

function browserSupportsWebSockets() {
    if ("WebSocket" in window)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Testing our application

Open the file websocket.html in either Google Chrome or Firefox current versions The following screenshot is a preview from Firefox

FireFox Browser WebSocket Support

Click on Send Message to WebSocket Server, You will get the following results

FireFox Browser WebSocket Support

Note: the bufferedAmount is 40 when the onsend event is fired. This is because the data is in the buffer queue. The value is zero (0) after firing the onmessage event. This is because is it the bufferedAmount is cleared when the message is sent to the server. Click on Close connection to the WebSocket Server, you will get the following window

FireFox Browser WebSocket Support

Note: the readState value is set to 2 (closed). Disconnect from the internet then refresh the application, you will get the following results.

FireFox Browser WebSocket Support

Note: the state is 3 which means the connection failed to open. Try to open the application in a web browser that does not support WebSockets i.e. Internet Explorer 9.

FireFox Browser WebSocket Support

Note: the event links and WebSocket attributes have not being displayed. This is because we removed them using JavaScript if the browser does not support.

Tutorial History

Tutorial version 1: Date Published 2015-07-24