Node JS - Get Real time online users counter using socket io example

December 14, 2017 | Category : Socket IO Node JS HTML

In this example, we lean how to get real time active users in mobile app or web application using nodejs

Sometime, we require to make functionality to get real time online users counter on your admin panel. We can easily do it using node js and socket io. I give you very simple example for real time online users counter that way you can simply use in your PHP project or any other language project. I created two files for this example as listed bellow:

1) index.html

2) server.js

First file is index.html, in this file we can run on browser and see how much active users on our web or mobile application using node. In second file we write logic of real time users counter using node and socket.

Make sure we you have installed nodejs, express and package of npm. So if you haven't installed this packages then install it before run this example.

Ok, So we will create two files as listed Above:


<!DOCTYPE html>



<title>Node JS - Get Real time online users counter using socket io example</title>

<script type="text/javascript" src=""></script>

<script type="text/javascript" src=""></script>



<h1>Conter : <span id="counter"></span></h1>

<script type="text/javascript">

var socket = io.connect('http://localhost:8001');

socket.on('counter', function (data) {







var app = require('express')();

var server = require('http').Server(app);

var io = require('')(server);


var count = 0;

var $ipsConnected = [];

io.on('connection', function (socket) {

var $ipAddress = socket.handshake.address;

if (!$ipsConnected.hasOwnProperty($ipAddress)) {

$ipsConnected[$ipAddress] = 1;


socket.emit('counter', {count:count});


console.log("client is connected");

/* Disconnect socket */

socket.on('disconnect', function() {

if ($ipsConnected.hasOwnProperty($ipAddress)) {

delete $ipsConnected[$ipAddress];


socket.emit('counter', {count:count});




Ok, now we are ready to run bellow example, so first open your terminal and run server.js file using bellow command:

nodejs server.js

Now you can run your index.html file and see the counter.

I hope you found best.....