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 socket.io.

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 socket.io 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:

index.html

<!DOCTYPE html>

<html>

<head>

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

<script type="text/javascript" src="https://code.jquery.com/jquery-1.4.2.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>

</head>

<body>


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


<script type="text/javascript">


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


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

$("#counter").text(data.count);

});


</script>


</body>

</html>

server.js

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

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

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


server.listen(8001);

var count = 0;

var $ipsConnected = [];


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


var $ipAddress = socket.handshake.address;

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

$ipsConnected[$ipAddress] = 1;

count++;

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

}


console.log("client is connected");


/* Disconnect socket */

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

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

delete $ipsConnected[$ipAddress];

count--;

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.....