Showing online users using Nodejs and Socket.io

In any Real Time chatting application showing a number of online users play very important role, which needs to be updated when a new user comes online or an online user goes offline. So this article explains how we can create such a list of online users.

Here we will use Nodejs for server-side, AngularJs for client-side and Socket.io for real-time updates. Also, in this application, we will create a login and registration functionality.Here we will use MongoDB in order to store user’s  information.

 

On this Blog, you will find private chat application implemented in Angular 1.x as well as Angular 2 and above.Make sure to check them out and if you feel like giving any suggestions or feature request then please let me know.

     Download

     Demo

Explanation :

  1. Okay, now let’s understand the working of this application, including the login, registration and fetching the list of online users along with the real-time updates for the list.
  2. First Users will log into the application or if a user is new to our application then he/she will have to register in our application.
  3. When the user completes the registration process, then we will redirect the user to the home page.
  4. On the home page first thing first, we will check the user is logged in or not. If yes then we will fetch the online users or else redirected user will be logged out.
  5. Now suppose any user is logged in our application and on some other machine any new user logs into the application than the rest of the logged in user will receive the socket event.
  6. That socket will carry the information of the newly logged in user. The figure shown below explains the working of this module.

showing number of online user workflow

Also, read Typing notification in chatting application using nodejs and socket.io

Assumptions:

  1. Here I am assuming A reader of this post is intermediate in Nodejs, So I won’t explain the login and registration functionalities.
  2. Also, all the CSS file you will find in the zip file.

Below you can see the directory structure for our server. In the utils folder, we have our config files, helper file which contains all the method and files to handle routes.

1. Directory structure and application configuration:

Directory structure:

Alright, now it’s time to get our hands dirty, let’s start from package.json file.Below is my package.json file or alternatively you can create your own by using npm init command.

package.json:

2. Creating a server:

Now let’s create our server.js file and write down the below code. In the below code, we will initialize the routes for the application and socket events. Also, we will add the application configuration for this current application setup.

As shown below, we will first setup configutation for the application and we will initiate the application’s routing and socket events.

server.js:

3. Creating Login and Registration

Here, I am not going to talk about the login and registration. You will find the code related to that in the source code of this application. The routes.js is fully utilized in the login and registration.

4. Implementing socket Event

Noe let’s create socket.js inside utils folder and write down the below into it.In this file, we will write the socket events which will push the real-time updates to the client.

socket.js:

Explanation:

In the above socket class, I have created two methods listed below,

  1. socketEvents().
  2. socketConfig().

Let’s start with socketConfig() method, In this method, if you notice we are storing the socket id and updating the online status of the user respectively who connects to chat application.
Here I am sending the user id of the user from the angular application, in order to update the socket id and online status.

In socketEvents() method, we are listening chat-list,logout and disconnect socket events on the server side.

  • On chat-list event: I am emitting the chat-list-response from the server for client-side.
  • On logout event: I am emitting the chat-list-response from the server for client-side by logging out the user.

Here we covered our server side application setup and created the REST API. Also, integrated the socket.io on the server side and created the events required for our application.

5. Creating helper file to run the MongoDB Queries.

Now let’s create a helper.js file inside utils directory and write the down below code. In the below code snippet, I have written each method’s name, description, and parameters required to that respective method.

helper.js:

6. Creating an Angular application.

Now let’s start the implementation of the front end. First we will start with login and registration, In order to do this let’s create index.html inside the views folder and write down below code. Below markup wrote for login and registration, here I am using UI bootstrap for AngularJs.

index.html:

Our login and Registration markup is completed, now let’s start the implementation of the home page. Create the home.html inside the views folder and write down the below code.

home.html:

Explanation:

The above markup is short and sweet, here first you will see the logout option then the ng-repeat for to iterate the list of online/offline users and at the end all the scripts that we have used.

Now let’s write down the AngularJs code, where we will create our AngularJs services and controllers. So let’s start from controllers, Create a script.js inside the public_data/js/ folder. In this file, we will create code login, registration, and home’s code.So basically we will have two controllers here one is for index.html and second on is for home.html. Write down the below code into the script.js file.

script.js:

Explanation:

In the above code,

First, we have created a socket factory method, where I am connecting socket server with the client by passing the userId of the user. Here I have created a separate class named as appService and I am using that class to create angular js service. We will take a look appService class after some time.

But before that let’s understand the both controllers. Here app controller si used for index.html, in other words, we are using the app controller for login and registration.I think the app controller is very easy to understand so I won’t talk much about it.

In the home controller, we have logic behind showing the online and offline user, So let’s break the code and understand it.

Here, we are capturing the userId of the user from the Url by using the appService class. If in any case userId found null or blank then on the next line we will redirect the user to login page.

Or else in the ideal situation, we will check the session by passing the userId of the respective user to userSessionCheck() which is defined inside the appService. If everything goes fine then we will connect the user to the socket.

Let’s get the list of online users, to do that we will use socket. The code to get the list of users goes inside the userSessionCheck() method for an obvious reason.

we are updating the list of the user, by using the socket on and emit event. For example, If a new user logs in into the system or an existing user goes offline in both the cases we will update the list of online users.

Now, here I am emitting the complete list of users to the user who just logged into the system.

And, the for the rest of users, those who are already online will get the users information who went offline or just logged in.

This makes sense, right? Because sending the complete list of online users to each and every user is not good.

Now if you see the above code there is else if() code block, http for the below task.

  1. If the response from the socket event contains the singleUser property which means the new socket connection is established.
  2. If the response contains the userDisconnected property then it means the user went and offline remove the user from the chat list.
  3. And at the end, In the else condition we will update the list of users in the else block.

Now the last part is remaining and i.e. is appService class. In this class, I have defined the method to create an HTTP request for login and registration and some other important for out application. So create a service.js class inside the public_data/js folder and write down the below code.

service.js:

7. Final thoughts:

So for this article that’s it.If you find this article useful consider sharing this on your social media and let the other people know about it and if you feel like giving me any suggestions please comment in below comment box.

Yes, I am working on the issue,

What if the process will be terminated unexpectedly? After restart process, old users will be yet marked as online.

I will add this fix ASAP and if you already have an idea about this issue, please comment below it will help other readers too.

  • xfg

    What if the process will be terminated unexpectedly? After restart process old users will be yet marked as online.

    • Nice catch, I’ll update this code.

      • xfg

        Is there any progress in this issue? What if the application is running within the node cluster, i.e. 2 or more processes and one of them died?

      • Brijesh prajapati

        how to run the app i m getting error when trying to login..
        in server.js line no 80. says can’t use the undefined property length