A Detailed Guide on Socket.io in Node.js

In 2010, Socket.IO was introduced. It was created to take advantage of open connections to promote real-time communication, which was still a new concept at the time. We know how Node.js is popular for developing enterprise-level applications, now, in this blog, we will learn about using Socket.io in Node.js and comprehend its role in real-time communication.            

What is socket.io?

Socket.IO allows client and server communication in both directions. When a client has Socket.IO installed in their browser and a server has also installed the Socket.IO package, bi-directional communication is possible. While data can be delivered in a variety of formats, JSON is the most straightforward.

Socket.IO uses Engine.IO to establish the connection and exchange data between the client and the server. This is a low-level implementation that is used behind the scenes. Engine.IO is used to implement the server, and Engine.IO-client is used to implement the client.

It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long polling or automatic reconnection.

Why do we need socket.io?

  • It takes care of all the deterioration of your technical options so that you can always have full-duplex communication.
  • It also deals with the program’s various levels of assistance and inconsistencies.
  • It additionally supplies extra component room support for the key distribution structure and acts as a planned reconnect.
  • AFAIK, it’s the most popular right now, and it’s easier to work with vanilla web attachments.
  • There are no restrictions. WebSocket and Socket.io Correlation (Infographics)

Highlights of Socket.io

  • It causes several attachments to communicate at the same time and manages the connection directly.
  • It covers every step, worker, and device, ensuring fairness, unwavering quality, and speed.
  • As a result, if necessary, it changes the requirement to WebSocket.
  • On top of several conventions, it is a custom continuous convention execution.
  • It is necessary to use the two libraries on the customer side as well as the worker side.
  • IO grinds away at based circumstances. Interface, message, Disengage, Ping, and Reconnect are some of the held events that can be accessed using the Attachment on the worker side.
  • Customers-based events such as interface error, interface break and reconnect, and so forth are managed.
  • Multiple underlying transports (WebSockets and long polling), capable of detecting and dealing with varied browser capabilities as well as disparate proxy capabilities, with smooth switching between transports.

Use cases

  • Gaming
  • IOT and connected devices
  • Healthcare
  • Automotive
  • Realtime chat applications and many more

Chat application using socket.io

A simple chat app is a common way to showcase the two-way communication capabilities of Socket.IO. When a new message is received by the server, it sends it to the client and notifies them, eliminating the need to send requests between client and server. This is demonstrated through a basic chat application.

  • Create folder and drop folder into vscode
  • Install socket.io and express using npm commands
cd socket.io-example          
	
npm install socket.io express
  • Setup node server and import required packages in index.js file.
const app = require('express')();
const http = require('http')

http.createServer(app);

const io = require('socket.io')(http);
  • The server root will send to  index.html which we will setup later on.
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));
  •  Now we setup Socket.IO in our chat app. It will listen for a ‘connection’ event and will run the function anytime this happens.

io.on("connection", function(socket) {
 console.log(“socket connected”);
});
  • now setup the server to listen on port 3000 for our index.html.
http.listen(3000, () => console.log("listening on http://localhost:3000")

  • The function io.emit()  is used to send a message to all the connected clients. This code will notify when a user connects to the server.
io.on("connection", function(socket) {
 io.emit(“user connected”);
});
  • We will also need to add a listener for any new messages received from a client and send a message to all users in response.
io.on("connection", function(socket) {
 io.emit(“user connected”);
 socket.on(“message", function(msg) {
   io.emit("message", msg);
 });
});
  • Here is an index.html file which includes a simple form with input for new messages and a container for displaying messages.
<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
   <title>Socket.io example</title>
 </head>

 <body>
   <h1>Socket.io Chat Application</h1>
   <div>
     <h2>Message</h2>
     
   </div>
   <form method="post">
     <input type="text" ></input>
     <button>Send</button>
   </form>
   <script src="/socket.io/socket.io.js"></script>
   <script>
    const Socket = io();
   </script>
 </body>
</html>
  • Will add Script logic in Script tag
<script>

 const form = document.querySelector("form");
 const input = document.querySelector("input");
 messageList = document.querySelector("ul");

 const socket = io();

 function sendMessage(e) {

   e.preventDefault();
   socket.emit("message", input.value);
   input.value = "";
 }

 form.addEventListener("submit", sendMessage);

 function addMessageToHTML(message) {
   const li = document.createElement("li");
   li.innerText = message;
   messageList.append(li);
 }
  // watch for socket to emit a 'message'
 socket.on("message", addMessageToHTML);

 function alertUserConnected() {
   addMessageToHTML("User connected");
 }
 socket.on("user connected", alertUserConnected);

</script>

Socket.io limits:

The first is that, in comparison to WebSockets, the first connection takes longer. This is because it uses long polling and xhr-polling to establish a connection before upgrading to WebSockets if they are available.

If you don’t need to support earlier browsers or aren’t concerned about client environments that don’t support WebSockets, Socket.IO may be unnecessary. You can reduce the impact by limiting your connections to WebSockets. The initial connection will be changed to WebSocket, but any fallback will be removed.

Future of Socket.io:

  • On 9th March 2021, Socket.io version v4 was released. And it is an API clean-up with several new features like the much-awaited support for Typed Events, Immutability, and several bug fixes.
  • npm downloads of the socket.io has increased but at a very low rate.
  • On the other hand, Sockjs and WS have been steadily growing and have outpaced Socket.IO in NPM downloads.
  • This suggests that, despite the rising use of sockets, developers have opted for alternatives to Socket.IO. Some people have gone with WS or SockJS. Others have chosen hosted solutions, which take care of the complexities of real-time messaging for you, and many of them have freemium models.
  • The most challenging part of utilizing sockets is scaling applications, and Socket.solution IO’s for non-WebSocket connections makes it even more difficult. The future of Socket.IO is similarly uncertain.

Conclusion

  • Socket.io is a powerful library, and we’ve just scratched the surface of its API. It has a lot more features, such as assigning namespaces to sockets so they have separate endpoints, creating rooms, and even integrating it with Redis. Check out their documentation if you want to learn more.

Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd.

Technocrat and entrepreneur of a reputed .NET development company with years of experience in building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals.

mm
Author
Ajay Patel – Technical Director, iFour Technolab Pvt. Ltd. A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. With a sharp understanding and technical acumen, he has delivered hundreds of Web, Cloud, Desktop, and Mobile solutions and is heading the technical department at an esteemed Microsoft 365 development company – iFour Technolab Pvt. Ltd. https://www.ifourtechnolab.com

Leave a Reply

Your email address will not be published. Required fields are marked *