Apps

What are Websockets- A Guide on The Basics of Socket.IO Implementation

Google+ Pinterest LinkedIn Tumblr

What are Websockets? WebSocket is a transport layer protocol that provides a persistent connection between client and server. This WebSocket operates over a TCP/IP socket connection and provides a full-duplex and bidirectional functionality for the communication. To simplify it, it works in a similar fashion as HTTP. HTTP is a protocol that sets the rules for how computers communicate, built on the concepts of requests and responses. Websockets are another protocol for sending and receiving messages, just with a slightly different structure. Regular Websockets (‘ws’ package in Node.js) generally requires two requests: The GET request for the actual HTML page, and another to UPGRADE the connection to WebSocket. This means that Websockets, in fact, use HTTP to send their fundamental requests – especially before the connection is upgraded to become persistent.

How do Websockets work?

In order to establish a WebSocket connection with the server, the client first sends an HTTP(S) “handshake” request with an upgrade header, specifying that the client wishes to establish a WebSocket connection. If the server is capable of establishing a WebSocket connection and the connection is allowed (for example, if the request comes from an authenticated or whitelisted client), the server sends a successful handshake response to confirm a successful connection.

Once the connection is upgraded, the protocol switches from HTTP to WebSocket, and while packets are still sent over TCP, the communication now conforms to the WebSocket message format. Since TCP, the underlying protocol that transmits data packets, is a full-duplex protocol, both the client and the server can send messages at the same time. Messages can be fragmented, so it’s possible to send a huge message without declaring the size beforehand. In that case, WebSockets breaks it up into frames. Each frame contains a small header that indicates the length and type of payload and whether this is the final frame.

A server can open WebSocket connections with multiple clients—even multiple connections with the same client. It can then message one, some, or all of these clients. Practically, this means multiple people can connect to our chat app, and we can message some of them at a time.

Finally, when it’s ready to close the connection, either the client or the server can send over a “close” message.

Websocket URL Structure

HTTP and Websockets differ in the way they start; however, in structure they are rather similar. 

HTTP URLs:

http://domain-name[:port]/resource-path/resource-id

WebSocket URLs:

ws://domain-name[:port]/resource-path/resource-id

HTTPS URLs (secured connection):

https://domain-name[:port]/resource-path/resource-id

WebSocket URLs (secured connection):

wss://domain-name[:port]/resource-path/resource-id

What is Socket.IO?

Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. Socket.io is built on the existing WebSocket technology; however, it is always ready to fall back to other technologies such as Flash Socket, AJAX Long Polling, AJAX Multipart Stream, and many more. This fall-back concept is what sets Socket.IO apart from the default WebSocket packages of Node.js – it allows Socket.IO to be used in contexts even where WebSockets are not supported. As a package, it will also handle a lot of the load-balancing and the smaller details, which would allow the developers to focus on the bigger picture of the project.

What is Socket.IO used for?

Socket.IO is a JavaScript library for real-time web applications. A real-time application (RTA) is an application that functions within a period that the user senses as immediate or current. In order to serve these real time applications, it is built with two parts − a client-side library that runs in the browser, and a server-side library for Node.js. Both components have an identical API.


Some examples of real-time applications are as following: 

  • Instant messengers − Chat apps like WhatsApp, Facebook Messenger, etc. You shouldn’t need to refresh the app/website to receive new messages.
  • Social Media Notifications − When someone posts a comment or tags you in a picture, you are immediately notified of the action.
  • Collaboration Applications − Apps like Google Docs allow multiple people to update the same documents simultaneously and apply any changes to all people’s instances.
  • Online Gaming − Online games often require you to be connected to a server to either interact with other players or to be 

Benefits and Drawbacks of Socket.io

One of the major benefits of Socket.IO is its capability to fallback on other technologies when Websockets are not supported. This allows those who use Socket.IO as in their development stack to serve more users despite the lack of optimal support for WebSockets on the users’ devices.

However, there are also a few drawbacks. Majority of modern-day web browsers support Websockets, and there are very, very few devices that don’t support it. While it is a great feature to have and a very nice feature to establish, there are very few circumstances where you would need that level of fallback support and redundancy. Socket.IO is also way more expensive in terms of network traffic. In fact, with plain WebSockets, the browser may need to run just two requests (as mentioned earlier in this post). Socket.IO takes significantly more requests to handle the same connection implemented in this package.

Basic Websocket Connection Requests

Socket.IO Connection Requests

‘socket.io’ Package Implementation

socket.io Server-Side Implementation

To install it on Node.js, you will need to run the following command: “npm install socket.io”

Here is some simple, sample code that one would expect to see on the Node.js Server-side with Socket.IO’s package properly installed and imported.

const io = require(“socket.io”)(3000);
io.on(“connection”, socket => {  // either with send() or with emit()  socket.send(“Hello! This is a Websocket connection!”);
  // handle the event sent with socket.send()  socket.on(“message”, (data) => {    console.log(data);  });
  // handle the event sent with socket.emit()  socket.on(“salutations”, (elem1, elem2, elem3) => {    console.log(elem1, elem2, elem3);  });});

socket.io Client-Side Implementation

Here is some sample code that one would expect to see on the Client-Side to connect to a server that uses Socket.IO.

const socket = io(“ws://localhost:3000”);
socket.on(“connect”, () => {  // either with send() or with emit()  socket.send(“Hello!”);});
// handle the event sent with socket.send()socket.on(“message”, data => {  console.log(data);});
// handle the event sent with socket.emit()socket.on(“greetings”, (elem1, elem2, elem3) => {  console.log(elem1, elem2, elem3);});

The WebSocket protocol is a wonderful tool to build real-time communication apps. A WebSocket connection is meant to be persisted, so can be overkill for simpler apps. However, it is important to remember that Server Sent Events (SSE) or plain old HTTP calls can be quicker and simpler to set up for rather simple applications. The decision of which to use will be up to the developer. However, for multiplayer games and collaborative apps, WebSockets opens up a world of possibilities.

Socket.IO is a great package to use in order to handle your Websocket needs. It greatly simplifies the overall development process and allows for the developer to focus on things that matter more in the bigger picture. We have seen how simple it is to get a simple server up and running, but the creativity on how to implement it for your own project is completely up to you. We wish you all the best on your project, and enjoy the development process!