Real-time Web App With Socket.io with React,Node.js, and Express.js

Jomon
4 min readMay 17, 2020

I believe we all would have come across a scenario where we need to push the changes from client to server and vice-versa. In most of the case, you may have used AJAX(Asynchronous JavaScript And XML) to do that without reloading the whole page. But in certain cases where we want to have a persistent connection to the server, Socket.io will be the best option. Let’s jump in and explore more about Socket.io.

What is Socket.io?

Socket.IO is a JavaScript library for Realtime web. It was developed in 2010. Socket.io is built on top of Engine.io — which is the WebSocket semantics transport layer. Socket.io is mostly compatible with all modern browsers except for some older versions of IE. Socket.IO allows bi-directional communication between the client and the server. It can be used for real-time analytics, binary streaming, Realtime messenger, etc.

How to use Socket.io?

Socket.io mostly useful when we have to maintain a persistent connection with the client and server. For eg:- We have a messenger application that is used by ’N’ number of users. So if one user starts typing in the message, we need to notify other users about it. In this scenario, Socket.io can be handy.

In order to start using socket.io in our application, we need to import Socket.io in our project. It has two different libraries. One which runs on the client-side in the browser and the other one which runs on the server-side.

Let’s start setting up Socket.io in our application.

Install the package in nodeJs

npm install — save socket.io

We need to import it in our application — (Server.js).

const socketIo = require(“socket.io”);

I am using Express in my application. Express is a Fast, unopinionated, minimalist web framework for Node.js. It's efficient and faster to develop compared to if we develop using node.js

const app = express();let server = require(‘http’).Server(app);let io = require(‘socket.io’)(server);

Let’s install the Socket.io package on our client-side. In my case, I am using react as my front end. We can use CDN as well.

npm install — save socket.io-client

Once we have installed the package successfully then we need to add our backend application URL in app.js (front-end).

const socket = io(‘http://localhost:5000/');

Socket.io uses on() and emit() method to emit and listen events.

on() method is used to listen to an event. It takes two arguments, first — the name of the event, second — call back function.

emit() method is used to emit a custom event. It takes three arguments, first — the name of the event, second — data object, third — call back function.

Socket.io has some reserved events like connection, disconnect, etc. Let's add a connection method in our server page. It will listen when a connection is established between the server and the client. It takes two arguments.

io.on(‘connection’, (socket) => {console.log(‘New Users Connected’);socket.on('disconnect', function(socket){        
counter = counter>0?counter-1:counter;
io.emit('totalUser',counter)
});
});

Now let’s try to emit and listen to some events from the client and server.

In app.js, let us add following code

const onChange = (e)=>{socket.emit(‘typing’,{username:username)})}useEffect(()=>{socket.on(‘someoneTyping’,(user)=>{setTyping(user.username +’ is typing…..’)}});},[])

In the above code, you can see I am trying to emit the ‘typing’ event from the onChange function and We want to let other users know about this event. So, in order to do that we need to listen to the event in using the on() and passing the event name to it. Once we listen to the event we can emit it back to all the connected users using emit() and listen to the event on our client-side.

In server.js, let us add following code

let counter =0;
io.on(‘connection’, (socket) => {
counter = counter+1;
socket.on(‘typing’,(user)=>{if(user!=undefined){io.emit(‘someoneTyping’,user)}})socket.on('disconnect', function(socket){
counter = counter>0?counter-1:counter; io.emit('totalUser',counter)
});
});

So you can see I am handling the event which is emitted by the client-side and re-emitting it so that all users will be able to listen to it. In the browser, you should be able to see the event which is emitted from the server.

Hope you all have got some basic idea about socket.io. You can get more information about Socket.io from their website.

I have developed a simple chat application that uses Socket.io with reactjs and nodejs. You can find the link below

Simple MERN Application with Socket.io

Summary

Socket.io is used for Realtime application. It may not be the best choice in all cases like when you need to just push some data to the server or perform the CRUD operation then HTTP calls are better because socket.io try to maintain a persistent connection with the server so in such cases it will be less economical choices.

Thanks for reading! :) If you liked it please support it by clicking the clap button.

Check out my other blog on the following:-

What Are React Hooks?

How can Console be used more efficiently by JavaScript developers for debugging?

Understanding High-Order Array Functions In JavaScript.

--

--

Jomon

I’m a software developer and a continuous learner. #reactjs #javascript #jquery #nodejs #erp #mongo #php