Closed goozmake closed 3 years ago
You are doing well, but you never remove values from yours on_connect/on_dissconnect. Try this:
var clients = null;
var ns1 = io.of('/ns1');
ns1.on("connection", socket => {
clients++;
console.log("connected clients", clients);
console.log("io.engine.clientsCount", io.engine.clientsCount);
socket.on("disconnect", socket => {
clients--;
console.log("user disconnected");
console.log("io.engine.clientsCount", io.engine.clientsCount);
console.log("disconnected clients", clients);
});
})
Or, there is another way, you can use method namespace.clients(callback) - from documentation https://socket.io/docs/server-api/#namespace-clients-callback
var clients = null;
var ns1 = io.of('/ns1');
function getClientsCouts() {
ns1.clients((error, socketsInRoom) => {
if (error) throw error;
console.log("clients in room", socketsInRoom.length);
});
}
ns1.on("connection", socket => {
clients++;
console.log("connected clients", clients);
console.log("io.engine.clientsCount", io.engine.clientsCount);
getClientsCouts();
socket.on("disconnect", socket => {
clients--;
getClientsCouts();
console.log("user disconnected");
console.log("disconnected clients", clients);
});
})
And dont forget to add this on Client side
const socket = io('/ns1');
Why do decrement of on_connect/on_dissconnect ? Count of websockets online is difference between on_connect and on_dissconnect. No?
For future readers: please see https://socket.io/docs/v3/server-instance/#Server-engine
I need to get count of websockets online.
I trying to calculate this that:
I have a problem: why onConnect-onDisconnect not equal "clientsCount"?
What is right way to calculate count of websockets online using events callbacks?
Stackoverflow