score:1

To keep the online status, you need to keep the users's online status in the database.

when a user is connected set it as online and on disconnect set it as offline. You can use a socket event to emit the users online status so that it will be reflected realtime

chatUtils

const redis = require('socket.io-redis');


module.exports = (socket)=>{

        global.io.adapter(redis({ host: redisUrl, port: redisPort}));

        global.io.on('connection', (socket) => {

                  try{
              //   Replace setOnlineOrOffline with your method . 
              setOnlineOrOffline(socket.handshake.query.userId,socket.id,true);
                  }
                   catch(e){
                  console.error(e)
                  }

  socket.on('disconnect', (a) => {
                //   Replace setOnlineOrOffline with your method . 
                   setOnlineOrOffline(null,socket.id,false);

            });

        });
};

App.js add

let socketio = require('socket.io');
let chatUtils = require('path-to-chat-util');

var socket = socketio(http, {
    transports: ['websocket', 'polling'],
    pingInterval: 60000
});

chatUtils(socket);

setOnlineOrOffline Function

module.exports.setOnlineOrOffline = (userId,socketId,status)=>{

   if(userId){
       // save userId,socketId,status To DB, keep socketId in an array since same user can connect from multiple browser tabs.

       // your save to db method.

       // emit the status to all users using, add necessary code to send data to all users.

              global.io.emit('onlineStatus',status);

      return
    }

}

If you planning to scale the server horizontally, use socket.io-redis module, and keep a redis server running outside the application servers.


Related Query

More Query from same tag