K
K
kr_ilya2019-11-24 13:10:54
Node.js
kr_ilya, 2019-11-24 13:10:54

How to count online on the site?

It is necessary to make an online counter on the site
node.js
socket.io

let online = 0,
    ipsConnected = []; //список подключенных ip

io.on('connection', async (socket) => {
    if(socket.handshake.headers['x-forwarded-for'] !== undefined){
      var address = socket.handshake.headers['x-forwarded-for'];
    }else{
      var address = socket.handshake.headers["x-real-ip"];
    }

    if(!ipsConnected.hasOwnProperty(address)) {
        ipsConnected[address] = 1;
        online++;
    }

socket.on('disconnect', () => {
        delete ipsConnected[address];
        online--;
  });

});

But this approach is not quite working. If you open the site, say, on a phone and on a PC, then online will be equal to 1. This is how it should be, because for all connections from one ip we consider online as 1. But if you close the site on one of the devices, online will be equal to 0, despite the fact that the person is still on the site.
What is the best way to implement an online counter? Or are there ready-made code examples for node and socket.io so as not to reinvent the wheel?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Taratin, 2019-11-24
@kr_ilya

socket.io has been out of date for a long time and does not give anything but an overhead.
Use net https://www.npmjs.com/package/ws
to get the number of all active connections wss.clients.length
https://www.npmjs.com/package/ws#server-broadcast
To weed out duplicates of multiple open browser tabs use session cookies with a random ID (cookies can be retrieved from request in this example https://www.npmjs.com/package/ws#client-authentication ).
How to get the ID assign it to the client ws.awesomeRandomId = <identifier>.
awesomeRandomId - an arbitrary name of your choice.
Further at https://www.npmjs.com/package/ws#server-broadcasteach client will have an awesomeRandomId, by which you can filter out duplicates.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question