I created a chat site using socket.io, node.js, nginx. But there is a problem with the number of online users. As soon as a new Internet tab is opened, a new user is added to the number of online users. If I open 10 new tabs, 10 new online users arrive. It is necessary that user count is unique IP amount! Thank you!
Connected
io.on("connection", async (socket) => {
// push current user in sockets
sockets.push(socket);
// get all users
const allSockets = await io.allSockets();
// emit the size of allSockets
io.emit("numberOfOnline", allSockets.size);
Disconnected
// remove the current user in sockets, searching, and notAvailable array if the user disconnects
sockets = sockets.filter((user) => user.id !== socket.id);
searching = searching.filter((user) => user.id !== socket.id);
notAvailable = notAvailable.filter((user) => user.id !== socket.id);
});
socket.on("disconnect", async () => {
// get all users
const allSockets = await io.allSockets();
// emit the size of allSockets
io.emit("numberOfOnline", allSockets.size);
});
2
Answers
Here is error log
If inside your
sockets
array contains only actual connections you can try this code