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

Disadvantages of 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

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,

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.