WebSockets | What are they & How are they Used?

WebSockets represent a long-awaited evolution in client/server web technology. They allow a long-held single TCP socket connection to be established between the client and server which allows for bi-directional, full-duplex, messages to be instantly distributed with little overhead resulting in a very low latency connection.

Both the WebSocket API and the well as native WebSocket support in browsers such as Google Chrome, Firefox, Opera and a prototype Silverlight to JavaScript bridge implementation for Internet Explorer, there are now WebSocket library implementations in Objective-C,.NET,Ruby,Java,node.js, ActionScript and many other languages.

WebSockets

WebSockets represent a big step in the evolution of the internet. Just as AJAX changed the game in the mid-2000s; having the ability to open bidirectional, low latency connections enable a whole new generation of real-time web applications. Including what I hope will be some pretty awesome games!

A brief history of the Web: developer’s perspective

The Internet wasn’t built to be all that dynamic. It was conceived to be a collection of HyperText Markup Language (HTML) pages linking to one another to form a conceptual web of information. Over time the static resources increased in number and richer items, such as images, began to be part of the web fabric.

Server technologies advanced allowing for dynamic server pages – pages whose content was generated based on a query. Soon the requirement to have more dynamic web pages lead to the availability of Dynamic HyperText Markup Language (DHTML) all thanks to JavaScript (let’s pretend VBScript never existed).

WebSockets

Over the following years, we saw cross-frame communication in an attempt to avoid page reloads followed by HTTP Polling within frames. Things started to get interesting with the introduction of LiveConnect, then the forever frame technique, and finally, thanks to Microsoft.

We ended up with the XMLHttpRequest object and therefore Asynchronous JavaScript and XML (AJAX). In turn, AJAX made XHR Long-Polling and XHR Streaming possible. But none of these solutions offered a truly standardized cross-browser solution to real-time bi-directional communication between a server and a client.

What kind of Apps can you Build with WebSockets?

So why would you want to use WebSockets (or something like it)? It’s not really about WebSockets; it is about what you are trying to get down to the TCP layer, send and receive small data packages, and make it reliable and available across a number of devices.

The ability to push a signal to a device as quickly as possible makes WebSockets one of the many solutions to push data between two devices. It’s the blueprint for creating realtime applications on both web and mobile (pretty much anything with a server and a client).

he WebSockets API and Protocol have both been standardized by the IETF and W3C, and have established themselves as a standard for realtime functionality in web, desktop, and mobile apps.

Some advantages of WebSockets include:

  • Cross-origin communication (however this poses security risks)
  • Cross-platform compatibility (web, desktop, mobile)
  • Low weight envelope when passing messages

However, the designation of WebSockets as the standard for data push and realtime communication is somewhat of a misnomer around the web as it is described today. Independent of some open-source solutions, WebSockets are just a part of the puzzle when developing realtime applications.

There are a slew of operational issues a developer may run into when using WebSockets as their realtime solution, especially as the app scales and the user base grows:

  • Network topology
  • Firewalls
  • Kernel configs
  • Load testing
  • Security
  • Monitoring
  • Scaling, redundancy, load balancing, replication

Overall, WebSockets are a powerful tool for adding realtime functionality to a web or mobile application.

Here: Check out how you can take WebSockets to the next level with PubNub.

How are WebSockets vs AJAX different?

WebSockets don’t make AJAX obsolete but they do supersede Comet (HTTP Long-polling/HTTP Streaming) as the solution of choice for true real-time functionality. AJAX should still be used for making short-lived web service calls, and if we eventually see a good uptake in CORS supporting web services, it will get even more useful.

WebSockets should now be the go-to standard for realtime functionality since they offer low latency bi-directional communication over a single connection. Even if a web browser doesn’t natively support theWebSocketobject there are polyfill fallback options which all but guarantee any web browser can actually establish a WebSocket connection.

How does WebSockets Work?

WebSockets provide new protocol between client and server which runs over a persistent TCP connection.

Because it is an independent TCP-based protocol, it doesn’t ideally require HTTP tunneling (similar to Netflix and other streaming services), allowing for simplified communication when sending messages.

How to use WebSockets

WebSockets comes after many other technologies that allow servers to send information to the client. Web applications that use Comet/Ajaxpush/pull and long polling all do this over HTTP. Other than handshaking the Upgrade Header, WebSockets is independent of HTTP.

The client establishes a WebSocket connection through a process known as the WebSocket handshake. This process starts with the client sending a regular HTTP request to the server. An Upgrade the header is included in this request that informs the server that the client wishes to establish a WebSocket connection.

Here is a simplified example of the initial request headers.

GET ws://websocket.example.com/ HTTP/1.1
Origin: http://example.com
Connection: Upgrade
Host: websocket.example.com
Upgrade: websocket

Note: WebSocket URLs use thewsscheme. There is also wss for secure WebSocket connections which are the equivalent of HTTPS.

If the server supports the WebSocket protocol, it agrees to the upgrade and communicates this through an Upgrade the header in the response.

HTTP/1.1 101 WebSocket Protocol Handshake
Date: Wed, 16 Oct 2013 10:07:34 GMT
Connection: Upgrade
Upgrade: WebSocket

What happens next?

At this point, either party can start sending data.

With WebSockets, you can transfer as much data as you like without incurring the overhead associated with traditional HTTP requests.

Next Step Resources;

  1. See the Demo
  2. Download The Code
  3. View on CodePen

Creating and Opening Connections

Creating WebSocket connections is really simple. All you have to do is call the WebSocket constructor and pass in the URL of your server. Copy the following code into your app.js file to create a new WebSocket connection.

// Create a new WebSocket.
var socket = new WebSocket('ws://echo.websocket.org');

Once the connection has been established the open the event will be fired on your WebSocket instance. You can handle any errors that occur by listening out for the error event.

Sending Messages

To send a message through the WebSocket connection you call the send() method on your WebSocket instance; passing in the data you want to transfer.

socket.send(data);

You can send both text and binary data through a WebSocket.

When the form is submitted this code will retrieve the message from themessageFieldand send it through the WebSocket.

The message is then added to themessagesListand displayed on the screen. To finish up, the valuemessageFieldis reset ready for the user to type in a new message.

Receiving Messages

When a message is received themessageevent is fired. This event includes a property calleddatathat can be used to access the contents of the message.

Your code should then retrieve the message from the event and display it in the messagesList. Once you’re done with your WebSocket you can terminate the connection using the close()method.

socket.close();

After the connection has been closed the browser will fire thecloseevent. Attaching an event listener to thecloseevent allows you to perform any clean up that you might need to do.

The developer tools in Google Chrome include a feature for monitoring traffic through a WebSocket. You can access this tool by following these steps:

  • Open up the Developer Tools.
  • Switch to the Network tab.
  • Click on the entry for your WebSocket connection.
  • Switch to the Frames tab.

These tools will show you a summary of all the data sent through the connection.

WebSockets on the Server

In this article, I have mainly focused on how to use WebSockets from a client-side perspective. If you’re looking to build your own WebSocket server there are plenty of libraries out there that can help you out.

One of the most popular is socket.io, a Node.JS library that provides cross-browser fallbacks so you can confidently use WebSockets in your applications today.

Some other libraries include:

Why are WebSockets a Game-changer?

Finally, WebSockets represent a standard for bi-directional real-time communication between servers and clients. Firstly in web browsers, but ultimately between any server and any client. The standards first approach means that as developers we can finally create functionality that works consistently across multiple platforms.

Connection limitations are no longer a problem since WebSockets represent a single TCP socket connection. Cross-domain communication has been considered from day one and is dealt with within the connection handshake.

This means that services such as Pusher can easily use them when offering a massively scalable real-time platform that can be used by any website, web, desktop or mobile application.

Further Reading;

I hope the above-revised guide on WebSockets was useful. But, if you’ll have additional contributions or questions, please Contact Us for more answers and explainers. Or simply, use the comments box below this post to share your thoughts and insights.

Finally, here are more useful and related to the topic links;

To Join Our Team:

Copyrights © 2019 | jmexclusives

Scroll to Top