Socket.io in NodeJS

Learn via video courses
Topics Covered

Overview

Socket.io in Node.js is an open-source library that uses WebSockets to create Real-Time and Scalable Web Applications. The goal of Socket.io is to help create fast and responsive applications by providing us with a full set of tools that help us to create and debug efficient code. Real-Time applications need to be fast and reliable so that they can deal with constantly changing real-time data. Socket.io library is used to create these applications in Node.js and examples of such applications include Real-Time Chat Applications, Multiplayer Games, Live Sports Match Tracking, etc.

Introduction to Socket.io in Node.js

When we think of communication` over the web, the initial thought is always, client-server communication. A client sends a request to the server which processes it, and then sends a response back to the client. This process is only efficient when the requested data doesn't change in real-time.

All of us have communicated using a chat application. We have also played games where the leaderboard is constantly updating. We might have also used stock and crypto applications where we see a constantly moving graph of data. All of the above are examples of Real-Time Applications. As the name suggests, these applications serve real-time data and have a negligible delay.

One of the most popular and widely used JavaScript libraries that are used to create such Real-Time Applications is known asSocket. io in Node.js. Users are presented with instant updates of data and the latency is very low. Think of this communication as if the client and the server are talking to each other on mobile. Through the course of this article, we will explore the Socket.io library in Node.js.

Introduction to Socket.io in Node.js

Why Use Socket.io in Node.js?

Let's say that we have a standard application that displays ball-by-ball commentary updates for a cricket match. If we want to refresh the data for every ball, then we have two options.

  1. We can either ask the user to keep refreshing the page every few seconds to send new requests to the server which will fetch the latest data. This process is terrible for user experience and is slow.
  2. We can set up an interval at the back end which will poll the server for the updated data. If the data is updated, then it would be sent to the client depending on a fixed time period. This process is called HTTP long-pooling. It is very resource-thirsty because it requires extra server overhead to maintain the pool and tracking the intervals. This makes it less than ideal when it comes to Real-Time Web Applications.

This is where WebSockets and Socket.io come into the picture. Socket.io in Node.js runs on both, the client and the server and help to establish WebSockets-based bi-directiona'lll communication. Here are a few features of Socket.io in Node.js:

  • Performance: As the connection is established using WebSockets, the communication has low latency and the overall communication channel will require less overhead.
  • Reliability: Socket.io in Node.Js is built to stand the test of extensive operations in multiple situations. The connection can be established through firewalls and other blockers. In case of connection failure, Socket.io falls to the HTTP long-pooling method. If the connection breaks for some reason, then Socket.io automatically tries to re-connect without needing manual intervention.
  • Scalability: A single connection can have multiple communication channels with Socket.io in Node.js. It is one of the most popular NPM packages and it is built to handle massive real-time data communication.

How Does the Socket.io in Node.js Work?

A modern web application has a client-side server and a back-end server. APIs are used for communication between them. Socket.io in Node.js is divided into two separate libraries.

  1. Socket.io: This is a server that sits on top of our back-end server. In our case, we will be demonstrating this using an Express.js server.
  2. Socket. io-client: This library is used on the client side of our application. In our case, we will be using an HTML page as our front end.

The communication here is an event-based system. The Socket.io in Node.js will help to listen to the connection and then the callback will give us access to the socket object. This object can be used to listen to any custom events. When an event is emitted, we will get access to the message with the event. This message can then be re-emitted back to the clients like a broadcast. A similar feature is established on the client side as well where the client can listen to messages via events and emit its messages to the back end.

bi-directional communication

We will be using these two libraries - socket.io and socket. io-client to establish a connection between the front end and the back end. This connection will help with bi-directional communication like sending messages. In the following sections, we will look at installing the libraries, setting up our back-end and front-end, and using Socket.io in Node.js to create Real-Time Applications!

Real-Time Applications

As the name suggests, a real-time application is an application working with real-time data. Data can change with time and sometimes the data changes extremely quickly. It is called Real-Time data when the data changes very frequently. Real-time data include stock data, live match data, etc. Here are a few examples of modern Real-time applications

  • Crypto-currency Exchange Application: Application for tracking real-time prices of crypto-currencies. Eg. Binance
  • Chat Application or Instant Messaging: Application for real-time communication between two or multiple people. Eg. Whatsapp, Facebook Messenger
  • Online Games: Multiplayer games that involve real-time party play are also using real-time communication. Eg. Valorant, Fortnite, etc.
  • Social Media: Instant notifications and updates use WebSockets.
  • Enterprise Work Applications: Applications that enable collaborative work where multiple users can work on the same project simultaneously. Eg. Google Docs, Sheets, Figma, etc.

All of the above-mentioned applications can be created using Socket.io in Node.js.

Examples of Real-Time applications

Installing Socket.io in Node.js

As discussed above, Scoket.io in Node.js is implemented using two libraries. For the back end we can install the socket.io library using the following command:

For the front end, we can install the `socket. io client library using the following command:

In the following section, we will delve deeper into the code for implementing connection using Socket.io in Node.js, sending messages, and creating our very own application using Socket.io.

Examples of Socket.io in Node.js Applications

Socket.IO in Node.js - Setting up the Environment

In this section, we will set up our environment for our Node.js application. First, we need to check if we have node.js and npm installed or not. Run the following commands one by one to verify this:

We are ideally looking for version 10+ for node.js. socket io nodejs If Node.js is not installed then we should download and install it from their website

Now we can proceed to set up our folder structure. Create a new project directory with the following command:

mkdir <Project Name>

Move into the new directory with the following command:

cd <Project Name>

Now we can initialize our node.js application using the following command:

npm init

Enter the required details in the terminal prompts or press Enter to skip further. socket io nodejs 2

Now let us install the two packages required to create our application. To install ExpressJS, run the following command:

npm install express

Now we will install our star package i.e, socket.io. Run the following command:

npm install socket.io

socket io nodejs 3

Socket.IO in Node.js - Internals

Internals refers to the machine working under the hood for Socket.io. Let's look into some of these mechanisms.

  • Fallback: When Socket.io cannot make a connection or when a connection breaks, there needs to be a fallback mechanism so that the communication doesn't stop. For eg, if WebSockets fail, then Socket.io will try to communicate using XHR long polling or XHR polling depending on a pre-defined order.
  • Connection: A connection using WebSockets or Socket.io initiates with a handshake. A handshake sets up socket-based communication. It happens using an HTTP request. Further communication happens using the socket.

Socket.IO in Node.js - Logging & Debugging

Socket.io sports very powerful debugging tools known as debug. The scope of debugging is separate from the server which makes debugging the application easier. This is because the debugging messages are not logged to the server console. We can separately log these messages. This is much more explicit in bigger applications. For our application, we will not even get a single debug log.

Socket.IO in Node.js - Error Handling

A small-scale local application like our Chat application will rarely throw any connection or timeout errors. However, at the industry level, this is not the case. Here, a developer needs to solve all client-side connection errors. The client API gives us a bunch of pre-defined events like Connect, Disconnect, Error, Message, etc. These events can be emitted according to the software requirement. We can use the on method in the index.html file(client) to handle these errors using events. Example:

Creating a Simple Hello World Application and Integrating Socket.io in Node.js

Now that we have our environment set up, we can start coding our back-end server. For the back end, we will use the ExpressJS package to create our server. Here is the snippet for server.js:

The above snippet will load the index.html file when the server is started and the user is on the / route. Below is the code for the index.html file

Here is what it looks like in the browser:

socket io nodejs 4

Now that we have our basic Hello world application ready, we will start filling this app with the goodness of Socket.io. We will edit the server.js with the code for the socket.io integration. Here is the snippet:

Here we can see that the HTTP server is passed to the Socket.io server to initialize it. Then we can use the on method to listen for events on the connection. The callback is used to handle the data. The count variable will track the connections and the users. Every time we will reload the page or open a new browser window, we will get a new connection and user.

Now we will edit the index.html file with the snippet to load the socket. io-client library. Refactor the code as below:

As we can see, the client library exposes an io() global to connect. We can specify the URL in the argument if we wish. By default, it will connect to the host server.

Now if we run the server and open multiple tabs of our browser window. Every time we open a tab, we can check the server console and we would have a new connection or user displayed. Here is the output we get when we open browser windows: Creating a Simple Hello World Application

Using Socket.io in Node.js to Build a Chat Application

Now let us turn our hello world application into a Real-Time Chat Application.

How to Emit Events using Socket.io in Node.js (Event Handling)?

Sending and Receiving events is what makes Socket.io in Node.js such a powerful library. Any data that can be parsed into JSON or binary can be emitted as an event. We will add a form to our index.html page(front-end). Whenever a user will enter a message in the form input field, the message will be logged in the server.js(back-end) console. This will be our very own chat message event.

We have added a form and another script tag to our index.html. Here is the snippet:

In the server.js file, we have changed the on method to the following:

Here is the browser window with the input message field:

Using Socket.io in Node.js to Build a Chat Application

Here is the server console:

Using Socket.io in Node.js to Build a Chat Application 2

Now that we have learned how to emit events, we can now discuss broadcasting.

How to Broadcast Messages Using Socket.io in Node.js (Real-Time Notifications)?

We have looked at creating multiple user connections using different browser windows and emitting events. Now we will emit events from the server to all the users. At the most basic level, we are just sending a message to all users.

We will edit our on method in the server.js file to the following:

Our index.html script will change to the following:

Now we can fire up two browser windows with our server and when we try to send a message from one of those, it is broadcasted to all the users. We can use the second window as well to send a message. All messages are listed using an HTML list. We have used two users as an example, however, we can have multiple users as well. This is how it looks in the browser windows:

Broadcast Messages Using Socket.io

We can also see that as soon as the message is sent from a user, it is broadcasted to all the users as an HTML list. Thus, we are not only sending and receiving the messages but also creating Notifications of the message. We can also make it so that all messages are logged to the server console.

Thus, we have successfully created a Real-Time Messaging/Chat Application with Socket.io in Node.js.

Node.js is changing the way we build web applications. Enroll in Scaler Topics course and become a part of this revolutionary shift in web development.

Conclusion

  • Socket.io in Node.js is a library that enables WebSocket-based bi-directional and real-time communication between client and server.
  • It has high performance, is extremely reliable, and can scale to bigger applications.
  • A Real-Time application works with Real-Time data like a Stock Exchange Application.
  • It is better to use Socket.io to create Real-Time applications as compared to sending multiple HTTP requests or HTTP long-pooling
  • Socket.io library has two parts: socket.io for the back-end server side and socket.io-client for the front-end client side.
  • Socket.io in Node.js can send real-time messages, emit events, and broadcast data. Collectively all the features can be used to make applications like a Real-Time Chat Application.
  • Other examples of Applications which uses Socket.io include Multiplayer Games, Sports Applications and Stock Exchange Applications.
  • The library is packed with in-built tools which can be used to debug the connection and handle errors.