display total number of online users currently node js

·

2 min read

Sometimes we require to display total number of available uses in our application. in node js we will follow these steps:

first step is to install socket.io package in your application using the following command : npm install --save socket.io

second step in your server file implement below code. we are creating a new port for our socket application which is 8888. in clients object we are assigning all the clients who are currently navigate our application. suppose in case any client move to other website from our application in this case disconnect method will trigger and we are deleting that particular client from our clients object

var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8888);
const clients = {};
io.on('connection', function (socket) {
  clients[socket.id] = socket;
  socket.emit('availableclients', {count: Object.keys(clients)});

  socket.on('disconnect', function() {
      clients[socket.id] = socket;
    socket.emit('availableclients', {count: Object.keys(clients)});
  });
});

Now the question is how we will get this information in our client end. we need to follow these steps. first we are accessing our socket js file from the port we have assigned in our server file which is 8888 then we are connecting to our web socket server and subscribe to the event we have created in our server which is availableclients. Now all the information we have on our client end and we can use this information as per our requirements.

client-socket.png