Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS - How Can You Tell If A Socket Is Already Open With The Einaros WS Socket Module?

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?

like image 882
Charlie Avatar asked Dec 12 '22 02:12

Charlie


2 Answers

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.

like image 90
jfriend00 Avatar answered Dec 13 '22 15:12

jfriend00


I think you should watch for the error and disconnect callbacks. That way you'll get notified when it closes.

like image 20
Max Avatar answered Dec 13 '22 16:12

Max