I'm currently using einaros' NodeJS WS module to create a websocket client. When initializing the socket client, I use the 'open' event to determine when the connection is open, but once it's open, how would I be able to check if it's still open?
Is there a property on the 'WebSocket' object that I can use to quickly check the status of the socket?
Is - websocketInstance.readyState - adequate?
socket.readyState
will tell you what the socket thinks its state is. There is no other, more accurate property that you can consult than socket.readyState
.
If what you want to know is when the socket has finished connecting and is now considered open, then you can register an event handler for the open
event. This will tell you when it has finished connecting.
If you want a real-time notification when the socket closes or experiences an error, you can use an event listener for the error
or close
events. The close
event just means that socket is closing and the socket.readyState
value is now changing to closed.
A more guaranteed to be up-to-date method of checking the socket is to first check socket.readyState
and, if that says the socket is open, then you can send a test packet to the other end and only when you get a response back from the test packet will you truly know that socket is operational.
The socket.io
library (built on top of webSockets) does exactly this, sending regular keep-alive packets and listening for responses. If it goes some period of time with no response, then it will close the existing socket and attempt to re-establish a new connection (figuring the prior connection was lost somehow). In this way, the socket.io
library can even survive a server reboot or a temporary drop in client internet connectivity as it will see that the connection was lost and then transparently re-establish a new connection in its place.
I think you should watch for the error and disconnect callbacks. That way you'll get notified when it closes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With