An Introduction to WebSockets

by PushRadar on April 28, 2021

In this article we take a look at WebSockets and how they have transformed the web, allowing for bi-directional realtime communication between server and client.

The Early Days of the Realtime Web

Let’s start at the beginning. You’ve probably heard of HTTP, right? Initially, the web was centred around the concept of a HTTP request. A client sends a HTTP request to a server for some resource or another. The server does some processing and returns some useful data to the client.

Importantly, this meant that the web was essentially a one-way stream; client requests, server fulfils. This underlying architecture of the web stayed in place for many years. People didn’t question it at first, but after some time the idea of a bi-directional web was floated. Imagine the power of having a server communicate data to clients in realtime without them first requesting it; would it somehow be possible to achieve such independent, active communication between both parties?

The invention of JavaScript by Brendan Eich in 1995 was a major step towards making the web realtime. With JavaScript, a web page’s user interface could be updated without a page refresh, meaning that for the first time, users could have a seamless web experience.

This was enhanced greatly by the invention of the XMLHTTPRequest (XHR) and AJAX. With AJAX, a HTTP request could be made to a server behind the scenes without user intervention, and the result of such a request could be used in a myriad of ways, most commonly to change the state (UI) of the page using JavaScript. As AJAX could be used to get data from a server on demand at regular intervals, not only could users have a seamless web experience, but now they could have a quasi-realtime web experience too.

The technique of requesting data from a server at regular intervals as described above is known as polling. Although initially used by many sites out of necessity, polling is now considered largely unsuitable for scalable client-server interaction due to the large overhead of each request, in the form of headers and cookies which are (in many cases, needlessly) sent across. Surely there must be a better way?

The XMLHTTPRequest proved to be quite versatile. The desire for realtime, bi-directional communication between server and clients meant that some inventive techniques arose which repurposed the XMLHTTPRequest to allow for data to be passed from server to clients seemingly on-demand. These techniques, exploiting long held HTTP connections were early examples of what would become known as Comet.

Long polling is perhaps the most well-known Comet technique. With long polling, an asynchronous HTTP request is initiated by the client and kept open until the server has some data to send. When the client has received a response (data) from the server, it immediately sends another request to the server and the process continues. It follows that with this method a connection is almost always open between the client and server, allowing for a sense of bi-directionality and realtime.

Another version of long polling involves using dynamically created script tags to point to a remote resource that returns JavaScript that is executed in the current document.

Although somewhat useful, the long polling technique is prone to errors and is unsuitable for small messages due to the large overhead; at its core, it’s using technology which was not purposed for bi-directionality and the request object is the same as that used with polling.

Enter WebSockets

Beginning in 2008, it was suggested that there could potentially be a better way to achieve realtime, full-duplex (two-way) communication between a given client and server. The WebSocket protocol was devised for this very purpose.

WebSockets are a thin layer on top of an underlying TCP/IP stack. This means that they actually act over a TCP connection, the same as HTTP. They can operate over the same ports as HTTP too, 80 and 443, and have their own URI scheme, ws:// and wss://, the latter being used for secure connections, in the same way that https:// is used for secure HTTP connections.

WebSockets aim to provide a means for two-way, client-server communication to happen in realtime, with minimal overhead. In other words, they facilitate quick message exchanges between a client and a server; a conversation, if you may.

WebSockets were introduced in Google Chrome 4 in 2010 and most other browsers followed suit. As of the time of writing, all major browsers support WebSockets (98.42% coverage worldwide).

Opening a WebSocket Connection

It’s straightforward to open a WebSocket connection using JavaScript. The following code is all you need:

var socket = new WebSocket("wss://");

The WebSocket Handshake

Opening a WebSocket connection initiates what’s called a handshake between the client and the server. The handshake does a few things, but primarily it negotiates upgrading the underlying HTTP connection to use the WebSocket protocol and ensures that no third party has been involved in falsely requesting a WebSocket connection in place of the client.

Under the hood, to establish a WebSocket connection, a client must send a request with an Upgrade header as follows:

WebSocket Request
GET / HTTP/1.1
Connection: Upgrade
Upgrade: websocket

The server then responds as follows (for example):

Server Response
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: a8raz3Lr22hfqAjtCxWigVwhpaB=

Not displayed above, but in addition to the Upgrade header, the client must send a Sec-WebSocket-Key, which is then transformed by appending the GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11. The resulting string is hashed and returned in the response, as the Sec-WebSocket-Accept header. This ensures that each WebSocket handshake is free from tampering.

Binding to Events

Once the handshake is complete, both parties can use the WebSocket connection to send data to one another. Client-side, we can bind to events on the WebSocket object to run code when the connection is opened and when a message is received as follows:

socket.onopen = function () {
    // Send a message to the server
    socket.send("Hello world!");

socket.onmessage = function (e) {
    // Log the data received

You can also bind to the onerror and onclose events, if desired.

Messages and Frames

Messages between the client and server over a WebSocket connection are exchanged in the form of frames. Messages can span multiple frames, in which case it is the responsibility of both parties to keep track of the frames they receive. An added benefit of using WebSockets is that the total number of frames does not have to be known in advance, so a party can get started processing the information they receive straight away.

What are WebSockets Used For?

WebSockets are most commonly used for realtime communication between a client and a server. They are inherently low-latency and full-duplex, and over the last few years they have transformed the web allowing for a realisation of realtime bi-directional user experiences.

There are a number of real-world practical applications for WebSockets, including realtime communication and instant messaging, screen sharing and collaboration, live updating content and streamed media.

WebSocket Servers: Use a Hosted Solution

The client-side code presented in this article is only a fraction of the picture. To start using WebSockets you will need to have a platform that handles client connections, probably with multiple servers for scalability and extra handling for pinging sockets, not to mention transport encryption and presence functionality.

PushRadar is a realtime publish-subscribe API service that provides a fully managed, hosted solution for realtime communication between your server and clients. Built with WebSockets at its core, our API solves all the infrastructure problems for you, so you can concentrate on what matters – your business.

Our Startup plan allows you to send 4 million messages per day to up to 2,000 connected clients. Get started today with a 5 day free trial.

Flexible realtime pub-sub API

Try PushRadar free for 5 days