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.
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.
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.
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).
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
- Kernel configs
- Load testing
- Scaling, redundancy, load balancing, replication
Overall, WebSockets are a powerful tool for adding realtime functionality to a web or mobile application.
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 the
WebSocketobject 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.
WebSockets comes after many other technologies that allow servers to send information to the client. Web applications that use Comet/Ajax, push/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 the
wsscheme. There is also
wss for secure WebSocket connections which are the equivalent of
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;
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
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.
You can send both text and binary data through a WebSocket.
When the form is submitted this code will retrieve the message from the
messageFieldand send it through the WebSocket.
The message is then added to the
messagesListand displayed on the screen. To finish up, the value
messageFieldis reset ready for the user to type in a new message.
When a message is received the
messageevent is fired. This event includes a property called
datathat 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
After the connection has been closed the browser will fire the
closeevent. Attaching an event listener to the
closeevent 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
- Click on the entry for your WebSocket connection.
- Switch to the
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:
- C++: libwebsockets
- Erlang: Shirasu.ws
- Java: Jetty
- Node.JS: ws
- Ruby: em-websocket
- Python: Tornado, pywebsocket
- PHP: Ratchet, phpws
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.
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;
- High-Performance Browser Networking: WebSocket
- IETF WebSocket Protocol
- WebSockets (MDN)
- WebSocket Specification (WHATWG)
- Can I Use: Web Sockets
Copyrights © 2019 | jmexclusives