0

I wan to to check if a specific socket is open. I am using socket.io. I assign the socket connection a name like

socket.username = username; 

when the connection is made, but is there a way to check if that is open from another connection? Basically checking if a user is online

I hope this makes sense.

Thanks

larry chambers
  • 473
  • 1
  • 6
  • 19
  • Depend on the app scaling. The easy approach would be to store every socket in an array. Then, you could use `.find()` to see if the connection already is open. – Izio Nov 22 '18 at 09:23
  • Have you tried `socket.readyState` ? – dral Nov 22 '18 at 09:26
  • That is what I was thinking about the arrays but I just thought if I know the socket name, there might be a quick way to check. – larry chambers Nov 22 '18 at 09:41

1 Answers1

0

Taking into account that network maybe slow, even if a given user is »online«/connected, it might easier to define »online« in terms of response time. So the easiest thing to do is to broadcast a »ping« event to a user and wait for its »pong« response. This way you not only check if the user is connected at all, because you can measure the response time as well and consider the user to be offline in case the response took too long.

Docs for a basic send/receive

update

So if I am getting this right, that might be the answer

philipp
  • 15,947
  • 15
  • 61
  • 106
  • I hear you but if the user disconnects, the socket is closed already so no need to ping it surely? // when the user disconnects.. perform this socket.on('disconnect', () => { --numUsers; console.log(socket.username+' has left, now there are '+numUsers+' online'); }); – larry chambers Nov 22 '18 at 09:47