KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

WebSocket API

Introduction

This tutorial serves as a basic introduction to web socket client side programming using JavaScript. The tutorial looks at the methods and attributes of the WebSocket API. We will create a simple client application that connects to the public Websocket server from www.websocket.org

Topics covered:

  • WebSocket API
  • WebSocket attributes, methods and events
  • Events
    • Open
    • Message
    • Error
    • Close
  • How to detect WebSocket support in client web browser

WebSocket API

A WebSocket API is an Application Programming Interface that enables web pages to use the WebSockets protocol for two-way communication with a remote host.

WebSocket attributes methods and events

If you are familiar with object oriented programming then using the WebSocket will be very easy for you.

Attributes

These are the attributes of the websocket class.

  • readyState – this is a read only attribute. It is unsigned short data type that is used to represent the state of the connection. You cannot set its value, you can only ready from it. It can assume the following four (4) states only.
    • 0 this is the default value. It means the connection has not been established to the server.
    • 1 This value means the connection to the server has been established and it is ready for communication.
    • 2 This value means the connection is closing.
    • 3 This value means the connection has being closed. It is also used when the connection fails to open.
  • bufferedAmount – this is a read only attribute. It is unsigned long data type that represents the queued data in bytes that has not yet being sent on the network. Its value increases when you call the send method

Methods

  • Send this method is used to transmit data to the server after a connection has been successfully established.
  • Close this method is used to close an active connection to the server.

Events

  • onopen this is the event that is called when a connection to the server has been successfully created. In other words, it is fired when the readyState changes to 1 (open).
  • onmessage this is the event that is called when data is received from the server on the client side.
  • onerror this is the event that is called when any error occurs
  • onclose this is the event that is called when the connection to the server has been successfully closed. In other words, it is fired when the readyState changes to 3 (closed)

Now that we have covered the basics of the WebSocket, let’s create a basic application that checks if the web browser you are using supports WebSockets or not. Older browsers do not support HTML5 and websockets, the application we are about to build comes in handy before you start executing any code that uses WebSockets.

How to detect WebSocket support in client web browser

For this application, you need to know the basics of JavaScript and HTML. You will also need an HTML editor. Most HTML editors support JavaScript as well. You can use notepad if you want but it does not support syntax highlighting so I suggest you use something like Notepad ++.

The following flowchart illustrates the logical flow of the program

Create a learning folder on your computer

Create a file named websocket_support.html in it

Add the following source code to the file

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Websockets support tester</title>
        <script type="text/javascript">
            function WebSocketSupport()
            {
                if ("WebSocket" in window)
                {
                    document.getElementById("ws_support").innerHTML = "<h2>Congratulations! Your web browser supports web sockets</h2>";
                }
                else
                {
                    document.getElementById("ws_support").innerHTML = "<h2>Sorry! Your web browser does not supports web sockets</h2>";
                }
            }
        </script>
    </head>
    <body onload="javascript: WebSocketSupport()">
        <div id="ws_support">
        </div>
    </body>
</html>

HERE,

  • <script>…</script> contains the Java script code
  • function WebSocketSupport() is the function that checks if the browser supports websockets
  • if ("WebSocket" in window) is the code that checks if the WebSocket is available in the window. It returns true if WebSocket is found in the window and false if it is not found.
  • <body onload="javascript:WebSocketSupport()"> calls the WebSocketSupport function using the body’s onload event. This event is fired when the page loads.

The rest of the code is standard JavaScript code that writes to a div in the body section depending on the value of the condition. Testing our application

Open the websocket_support.html in your browser.

Internet Explorer 9 – Does not support WebSockets

Internet Explorer 9 Browser WebSocket Support

Firefox 26 - Supports Web Sockets

FireFox Browser WebSocket Support

Google Chrome 32 – Supports Web Sockets

Google Chrome 32 Browser WebSocket Support

Tutorial History

Tutorial version 1: Date Published 2015-08-20