Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if socket is still open

Following instruction from my previous question, I now have an array of connected users in socket.io. My problem (which I was warned of in the answer) is that sockets stay in this array even after the browser has disconnected.

I tried removing sockets from the array in a socket.on('disconnect' function, but there is still a delay of ~1 minute between when the browser disconnects and socket.io triggers the disconnect.

What is the best way to "test" a socket to see if its actually alive? I am tempted to try to send a message and catch any errors, but I feel like there is a more elegant solution.

like image 577
MrGlass Avatar asked Sep 05 '25 17:09

MrGlass


1 Answers

Solution on how to test if "socket is still open"

if(socket.readyState === socket.OPEN)
{
}

Why it works:

readyState = The current state of the connection; this is one of the Ready state constants. Read only.

"the Ready state constants"
CONNECTING 0: The connection is not yet open.
OPEN 1: The connection is open and ready to communicate.
CLOSING 2: The connection is in theprocess of closing.
CLOSED 3: The connection is closed or couldn't be opened.

https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

like image 50
Olle89 Avatar answered Sep 08 '25 11:09

Olle89