Answer the question
In order to leave comments, you need to log in
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--;
});
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question