Voice of a Developer: Javascript WebSocket - Part 27

Introduction

 
JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
 
Before moving further let us look at the previous articles of the series:
In this article, we will understand WebSocket, which is a new revolution in client-server communication. Modern browsers support this protocol. The server shall also support WebSocket thus a handshake between client & server is possible.
 

WebSocket

 
It is based on ws schema and establishes a full-duplex connection between client & server. At the client-end, it is a browser and it can work with any server capable of running WebSocket protocol.
 

Advantages of WebSocket

  • Faster than TCP
     
    Quick response from the server where you are using an HTTP connection to connect. TCP connection lifecycle is SYN, SYN/ACK, ACK, and then send a GET request. TCP header contains 10 mandatory fields and an optional field. TCP has close ends at both sides – Refer a useful diagram from Wiki.
     
    diagram
     
    However, WebSocket simply receives the response with a small header.
     
  • Better than other methods like polling, AJAX
     
    For duplex communication, developers used a technique like polling to constantly synchronize with the server. This technique was never effective for duplex communication. Hence, WebSocket came into the picture.
     
  • Easy to use
     
    It is easy to use on both ends. At the server, it is independent of the platform too.

Disadvantages of WebSocket

  • Open connection
     
    The disadvantage is that it keeps the connection open on the server for the duration of the time user is interacting with the page. Therefore, it consumes more resources on the server.
     
  • Single-channel communication
     
    If your app does not need too much duplex communication with the server then you can think of using other approaches like long polling, AJAX over WebSocket.

WebSocket server

 
I suggest to use /download any server supporting WebSocket. In IIS, you can also enable WebSocket via adding Application Development features. For testing, I want to use WebSocket servers like UNIX.
 

Steps to run the server

  • Download WebSocketd from URL.
  • Extract the zip file in a folder like C:\websocket
  • The server is platform-independent and can run any program
  • Create a server program in C# and build to generate myProgram.exe,
    1. using System;    
    2. using System.Threading;    
    3.     
    4. //myProgram.cs    
    5. class Counter    
    6. {    
    7.     static void Main()    
    8.     {    
    9.         for (int i = 1; i <= 10; i++)    
    10.         {    
    11.             Console.WriteLine(i);    
    12.             Thread.Sleep(500);    
    13.         }    
    14.     }    
    15. }   
  • You can copy myProgram.exe into c:\websocket for convenience
  • Open a command shell and goto c:\websocket and run below command
  • websocketd.exe -- port 80 myProgram.exe
cmd
 
It gave the above error because port 80 is already in use. We can validate by using netstat command.
 
cmd
 
So I will use port 8082 to run the WebSocket server.
 
websocketd.exe -- port 8082 myProgram.exe
 
cmd
 

WebSocket client object

 
With this API, you can send and receive messages to a server without having to poll the server.
 

Receiving messages

 
After the connection is established, we can receive messages using onmessage event.
  1. var ws = new WebSocket('ws://localhost:8082/');    
  2. // this will establish connection with server at port 8082    
  3. //notice ws: this is new URL schema for WebSocket connection    
  4. ws.onmessage = function(event) {    
  5. console.log('Count is: ' + event.data);    
  6. }; // this will receive output from server in event.data   
 
output
 

Sending messages

 
After the connection is established via onopen event, we can send messages using the send method.
  1. ws.onopen = function () {    
  2. console.log('OnOpen');    
  3. ws.send('my message');    
  4. }   

Log errors

 
Use onerror event to trap error generated from WebSocket,
  1. ws.onerror = function (error) {    
  2. console.log('WebSocket Error ' + error);    
  3. };   

ReadyState

 
If you remember, we have a ready state in XHR API. Similarly, WebSocket also maintains a connection state. It starts from 0 to 3, 
  • 0 | Connecting- the connection is not yet open
  • 1 | Open- the connection is open & ready to communicate
  • 2 | Closing- the connection is closing
  • 3 | Closed- the connection is closed

Close

 
To close an open connection use close method, like ws.close();
 

Summary

 
The web is full of technologies and the intent is to make the web fast & better than before. Our quest shall be to give users good experiences and good performance applications. Please share your feedback/comments.


Similar Articles