Implementing WebSocket API



Implement a callback

Callbacks are a design pattern to implement when you are working with multiple threads or just needing to have something work asynchronously.

The idea of a callback is to call a function to run but when it’s done, to call back a specified function with usually some sort of result or status of the operation.

The general callback pattern is shown in the following code:

<body>
<input type="submit" onclick="callbackFunction()" value="Callback Function" /><br />
<div id="#div1"> </div>
<!-- CallBack -->
<script type="text/javascript">
    var callbackFunction = function () {
        WillCallBackWhenDone(MyCallBack, 3, 3);
    }
    function WillCallBackWhenDone(f, a, b) {
        var r = a * b;
        f(r);
    }
    function MyCallBack(result) {
        document.getElementById("#div1").innerHTML = ("The Result is: " + result);
    }
</script>
</body>

WebSocket API

The WebSocket API provides bidirectional communication support to web applications.

The use of the WebSocket API allows the connection directly to a server over a socket. This is a much lighter weight connection and is fully bidirectional; both binary and text-based data can be sent and received.

WebSocket API is ideal for real-time applications such as messenger/chat applications, server-based games, Real-Time Communication, video conferencing etc..

The primary object that you will work with is the WebSocket object, which connects to the socket when its constructor is invoked.

<script type="text/javascript">
    connectButton.onclick = function () {
        //Or the use of wss for secure WebSockets.
        wsConnection = new WebSocket('ws://localhost:8080', ['soap', 'xmpp']);
        }
    }
</script>

The WebSocket constructor accepts two parameters:

  • The URL of the server-side socket to connect to, which is always prefixed with ws or wss for secure WebSocket connections
  • An optional list of sub protocols

When the WebSocket constructor is called, the WebSocket API establishes a connection to the server.

WebSocket API provides two events to handler the connection:

  • onopen event handler when connection is established
  • onerror when the connection will fail

The following code implement the onopen and the onerror events:

<script type="text/javascript">
    // event handler for when the WebSocket connection is established
    wsConnection.onopen = function () {
        chatBox.textContent = chatBox.textContent + "System: Connection established";
    }
    //event handler for when the WebSocket encounters an error
    wsConnection.onerror = function (err) {
        //write an error to the screen
        NewLine();
        chatBox.value = chatBox.value + "System: Error Occurred. ";
    }
</script>

When a successful connection is established, you can send and receive messages over the socket. WebSocket API provides two methods:

  • the Send function to send messages
  • the onmessage event handler to receive messages

The following code implement the two methods:

<script type="text/javascript">
    wsConnection.onmessage = function (msg) {
        //write message
        NewLine();
        chatBox.value = chatBox.value + "Them: " + msg.data;
    }
    sendButton.onclick = function () {
        //check the state of the connection
        if (wsConnection.readyState == WebSocket.OPEN) {
            //send message to server.
            wsConnection.send(msgToSend.value);
    }
    else return;
        //show message in chat window.
        NewLine();
        chatBox.value = chatBox.value + "You: " + msgToSend.value;
        //clear message text box
        msgToSend.value = '';
    }
</script>

The WebSocket API provides a mechanism to check the current status of the connection. To prevent an error, the readyState property is evaluated to ensure that it’s now open.

In the following table are described the possible values of the WebSocket readyState

Value Description
OPEN The connection is open.
CONNECTING The connection is in the process of connecting and not ready for use yet. This is the default value.
CLOSING The connection is in the process of being closed.
CLOSED The connection is closed.

When finished with a chat session, a user should be able to exit cleanly by calling the close method of the WebSocket object.

The close method can be called with no parameters. It also allows the use of two optional parameters: a numerical code and a reason can be provided but isn’t mandatory. When a connection is closed, the onclose event handler is raised:

The following code implementing bidirectional communication with the WebSocket API:

<head>
<script type="text/javascript">
    window.onload = function () {
        var wsConnection;
        var chatBox = document.getElementById("chatWindow");
        var disconnectButton = document.getElementById("Disconnect");
        var connectButton = document.getElementById("Connect");
        var sendButton = document.getElementById("Send");
        var msgToSend = document.getElementById("msgSendText");
        disconnectButton.onclick = function () {
            wsConnection.close();
        }
        connectButton.onclick = function () {
            //Or the use of wss for secure WebSockets.
            wsConnection = new WebSocket('ws://localhost:20284', ['soap', 'xmpp']);
        }
        sendButton.onclick = function () {
            //check the state of the connection
            if (wsConnection.readyState == WebSocket.OPEN) {
                //send message to server.
                wsConnection.send(msgToSend.value);
            }
            else return;
            //show message in chat window.
            NewLine();
            chatBox.value = chatBox.value + "You: " + msgToSend.value;
            //clear message text box
            msgToSend.value = '';
        }
        // event handler for when the WebSocket connection is established
        wsConnection.onopen = function () {
            chatBox.textContent = chatBox.textContent + "System: Connection established";
        }
        //event handler for when the WebSocket encounters an error
        wsConnection.onerror = function (err) {
            //write an error to the screen
            NewLine();
            chatBox.value = chatBox.value + "System: Error Occurred. ";
        }
        wsConnection.onclose = function () {
            //write the connection has been closed.
            NewLine();
            chatBox.value = chatBox.value + "System: Connection closed.";
        }
        wsConnection.onmessage = function (msg) {
            //write message
            NewLine();
            chatBox.value = chatBox.value + "Them: " + msg.data;
        }
        //helper functions.
        function NewLine() {
            chatBox.textContent = chatBox.textContent + '\r\n';
        }
    }
</script>
</head>
<body>
    <div align="center">
        <div> Infocodify Tutorials Exam 70-480 HTML5, CSS3 & JavaScript</div>
        <div>
            <textarea id="chatWindow" style="height: 500px; width: 300px"></textarea>
        </div>
        <div>
            <input type="text" id="msgSendText" style="width: 300px" />
        </div>
        <div>
            <button id="Disconnect">Disconnect</button>
            <button id="Connect">Connect</button>
            <button id="Send">Send</button>
        </div>
    </div>
</body>

Ads Right