How to create a offline/online features using websocket


Hi, I am trying to implement a online status feature using web socket.

Things that I think I need to do is

  1. When user is connected, let the other users know. I can do this step from client side like this.
ws.on('open', () => {
    isConnected = true
// based on isConnected I can let all of his friends know about his connection. 

But here I want to avoid,

  • Lets say this user is connected from one tab and the code already let others know and updated his user table for online status. But he opens a new tab this same code will re execute, so its a waste of resource. How can I avoid this? (May be I can avoid it checking user object from db)
  1. How can I know when user is disconnected so that I can send offline flag to the database and do other task? I can do this using server side may like this
onClose (d) {
    // same as: socket.on('close')
        console.log('I am closing....')

  • The problem of this is, I need to know who is disconnected. From the console log of this.socket is
I am closing down....
Socket {
   Channel {
     name: 'noti:*',
     _onConnect: 'NotifyerController',
     _channelControllerListeners: [ [Object], [Object], [Object] ],
     subscriptions: Map { 'noti:2' => Set {} },
     _middleware: [],
     deleteSubscription: [Function: bound ] },
  emitter: Emittery {} }

// here noti:2 is a dynamic topic where 2 is the id of the disconnected user.
a. I need to get this id (2). (I can know this id from Auth.user but how can I run this inside this method. )
b. I need to be able to run a database query so that I can update status in db.
c. Lets say, two tabs were opened, if one is closed still another one is opened so user is still online, how can check if he has any active subscription?

This whole thing can be implemented in many ways. I know only this, if anyone of you can suggest would be really helpful.

Many thanks.