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.
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,
- using System;
- using System.Threading;
-
-
- class Counter
- {
- static void Main()
- {
- for (int i = 1; i <= 10; i++)
- {
- Console.WriteLine(i);
- Thread.Sleep(500);
- }
- }
- }
- 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
It gave the above error because port 80 is already in use. We can validate by using netstat command.
So I will use port 8082 to run the WebSocket server.
websocketd.exe -- port 8082 myProgram.exe
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.
- var ws = new WebSocket('ws://localhost:8082/');
-
-
- ws.onmessage = function(event) {
- console.log('Count is: ' + event.data);
- };
Sending messages
After the connection is established via onopen event, we can send messages using the send method.
- ws.onopen = function () {
- console.log('OnOpen');
- ws.send('my message');
- }
Log errors
Use onerror event to trap error generated from WebSocket,
- ws.onerror = function (error) {
- console.log('WebSocket Error ' + error);
- };
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.