Title Image
Home  /  Technology   /  An Introduction to Websockets: Beginners Guide
Websocket building real time application

An Introduction to Websockets: Beginners Guide

“Real-time” is becoming the new norm for modern application development, as more and more consumers today demand faster access to data. While interacting with applications in real time has become routine for many of us, developing an application that ensures a flawless and positive user experience still seems to be the Holy Grail for developers.

What’s Stopping Developers from Building Real-Time Apps?

Web application developers are more familiar to HTTP based request / response stateless transactions and are usually unaware of the full duplex bi-directional mechanism which is now exposed to them via the WebSocket Protocol. Though HTTP and RESTFul approach makes development an easy task, however, the applications often fail in delivering real-time due to the request / response nature of the transactions. To overcome this, many strategies were devised initially to create an illusion of server-initiated transactions. But among all the strategies, the most popular was long-polling and Comet– a technique that keeps an HTTP connection open until the server has some new data to send as a response to the client. These techniques prevailed for sometime until the Websocket Protocol came into existence.
Also there were many caveats with using long polling listed as below:

  • Since it creates a connection each time an HTTP request is made, more than one header and cookie data gets transferred to the server, producing additional overhead.
  • Not suitable for scalable applications that require high frequency.
  • Long polling is based on request-response and isn’t a push technology, so you are likely going to have to address some level of hindrance in establishing a persistent connection.

Above are a few reasons that make the long-polling technique not good enough for scalable and real-time communication on the web. Clearly, we needed a better solution for implementing real time functionality. And this is why WebSockets evolved.

The What and How of WebSockets

WebSockets are a way of creating a persistent connection between browser and server with lower overheads than an HTTP protocol. In plain words, WebSocket Protocol exposes the underlying TCP socket to the Application layer for the application developers to leverage and create application that require bi-directional flow of information.

How do WebSockets work? The Handshake

Before sending and receiving messages, a connection needs to be established between the client and server. The connection is established through a process called as WebSocket handshake. This process initiates with the client sending out a request to connect to the server (which resembles the HTTP model of request-response). An upgrade header is sent in the request to inform the server that the client wishes to establish a WebSocket connection.

This is how the client initiated handshake request looks like:

GET /chat HTTP/1.1
Host: server. example.com
Upgrade: Websocket
Connection: Upgrade
Sec-WebSocket-Key: x2JJLMbDR1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://newexample.com

How do WebSockets work The Handshake

Note: Keep in mind that WebSocket URLs make use of the ws scheme. But for more secure WebSocket connections you should use “wss” – just like “https:” is used for secure HTTP connections.

The response from the server to the client’s handshake request looks like:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HJprc0sMLYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

Once the handshake gets completed the initial HTTP connection is substituted with a WebSocket connection that makes use of the same underlying TCP/IP connection.

The biggest advantage of using WebSockets is how it enables you to transfer huge chunks of data without the HTTP overhead and how data of unknown sizes can be sent using the base framing defined by WebSocket Protocol.

Note: I will cover the base framing in a separate blog post. For this one, I would like it to be for the beginners.

The WebSocket API

Web developers will likely be more interested in learning about the WebSocket API (a JavaScript based API), as it enable web applications to open a bidirectional connection with server-side processes.

When it comes to working with the WebSockets API, the first thing that developers should do is detect whether the API is supported by the client browser or not. This can be achieved using the following code snippet:

//Checking whether the browser support WebSockets
if ('WebSocket' in window){
/* WebSocket is supported. You can proceed with your code*/
} else {
/*WebSockets are not supported. Try a fallback method like long-polling etc*/
}

Opening and Closing WebSocket Connections

If the WebSocket API is supported by the browser, you can open up a WebSocket connection to the server by calling the WebSocket constructor:

var connection = new WebSocket('ws://server_address’);

Once the connection to the server is established, the open event will be fired on the client’s side. Using the following code snippet will update you once the connection has been established:

connection.onopen = function(){
/*Once the connection is established send a small message to the console*/
console.log('Connection open!');
}

But in case the server refuses your connection, or the connection gets closed for some reason, then the onclose event is fired.

connection.onclose = function(){
console.log('Connection closed');
}

For handling any errors, simply use the onerror event as shown in the code below:

connection.onerror = function(error){
console.log('Error detected: ' + error);
}

Sending and Receiving Messages

Once a connection to the server is established, you can start sending messages to and from the server. To send a message, you simply need to call the send() method on your connection object:

connection.send(‘message');

Once the client receives a message the onmessage event is fired. Further, the message event contains a property called data that helps in accessing the message contents.

connection.onmessage = function(event1){
var server_message = event1.data; console.log(server_message);
}

WebSockets : The sever side story

Although there are multiple libraries and commercial implementations available both on premise and as a service. If you plan on building your own WebSocket server I suggest you to look at RFC 6455. Below is a list of Websocket servers / libraries you can use:

JavaScript: Socket.IO
C: libwebsockets
C++: Websocketpp
Erlang: Shirasu.ws
Java: Java-WebSocket
PHP: Ratchet, phpws
Ruby: em-websocket
Python: Tornado, pywebsocket

Use Cases for WebSockets

You should consider using WebSockets for building real-time components of your applications that requires a truly low latency. Some of the best known use cases for WebSockets are:

  • Chat messaging application
  • Multiplayer online games
  • Live sports updates, etc.

Tip: Reading Top 10 Worthwhile Uses of WebSockets will help you know in what cases WebSockets should be used.

What browsers support WebSockets?

Today almost all modern browsers support WebSockets except may be a few. To get up-to-date information related to browsers that support WebSockets refer to: Can I use Web Sockets.

Final Thought

WebSockets is a great technology that overcomes the problems we face with the traditional HTTP model of client-initiated interactions. This technology is best fit for applications that require generating high amount of data instantaneously, and which needs to be communicated in real-time.

However, the use of WebSockets is often limited to web browser clients. While you can use WebSockets to build highly-interactive web applications, to deliver the same experience on mobile applications that update in real-time you will need to do some extra work on both client and server side. Moreover, considering the fact that the landscape of browsers and devices is constantly changing, WebSockets might not be supported by the choice of your browser/device. We need a solution that enables developers to engage in deploying real-time solutions without having to worry about the ever-changing set of techniques and environments. And That’s where PushFYI comes to your rescue.

PushFYI is a full-duplex data stream server that empowers developers in implementing real-time capabilities into web and mobile applications using the WebSocket technology. PushFYI APIs support multiple programming languages, which ensures that developers can use the programming environment of there choice to start using Websockets. Visit us at pushfyi.com to get started now.

Post a comment

PushFYI Open Source available on GitHub