skip to Main Content

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


  1. Chosen as BEST ANSWER

    Here is error log

    2021-02-12T20:58:16.084895+00:00 app[web.1]: npm ERR! 
    2021-02-12T20:58:16.084962+00:00 app[web.1]: npm ERR! Failed at the [email protected] start script.
    2021-02-12T20:58:16.085040+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    2021-02-12T20:58:16.092404+00:00 app[web.1]: 
    2021-02-12T20:58:16.092658+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
    2021-02-12T20:58:16.092791+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2021-02-12T20_58_16_085Z-debug.log
    2021-02-12T20:58:16.163256+00:00 heroku[web.1]: Process exited with status 1
    2021-02-12T20:58:16.271729+00:00 heroku[web.1]: State changed from starting to crashed
    2021-02-12T20:58:17.036652+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=app.herokuapp.com request_id=3b2edd32-47b7-4549-a8df-3f80cab096f5 fwd="46.109.220.2" dyno= connect= service= status=503 bytes= protocol=https
    2021-02-12T20:58:43.051339+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=app.herokuapp.com request_id=8955b076-bf77-4003-ac86-a18d27e3300a fwd="46.109.220.2" dyno= connect= service= status=503 bytes= protocol=https
    

  2. If inside your sockets array contains only actual connections you can try this code

    const ips = new Set();
    sockets.map(item=>ips.add(item.request.connection.remoteAddress));
    
    console.log(ips.size);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search