Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current status of a javascript websocket connection

Sometimes when I restart the server or there is a network failure the websocket gets closed and I would like to be able to get the current connection status at all time.

I am basically getting the following error and I want to be able to predict it :

WebSocket is already in CLOSING or CLOSED state. 
    (anonymous function) 
    InjectedScript._evaluateOn 
    InjectedScript._evaluateAndWrap 
    InjectedScript.evaluate
like image 853
Johnride Avatar asked Apr 29 '14 15:04

Johnride


People also ask

How do I check my WebSocket connection status?

You can check if a WebSocket is connected by doing either of the following: Specifying a function to the WebSocket. onopen event handler property, or; Using addEventListener to listen to the open event.

How do you know if a WebSocket is closed?

You can check if a WebSocket is disconnected by doing either of the following: Specifying a function to the WebSocket. onclose event handler property, or; Using addEventListener to listen to the close event.

Which WebSocket attribute indicates the connection ready status?

Socket.readyState A value of 0 indicates that the connection has not yet been established. A value of 1 indicates that the connection is established and communication is possible.

How do I know if a WebSocket is open in Terminal?

A way to work if it's open is : if (yourWsObject. readyState === WebSocket.


1 Answers

This is very straightforward : thereadyState property of the websocket contains the connection of the websocket at all times as specified in the WebSocket API

It will be one of the following values : CONNECTING OPEN CLOSING or CLOSED

A way to work around the error would be something like this :

if (yourWsObject.readyState !== WebSocket.CLOSED) {
   // Do your stuff...
}
like image 142
Johnride Avatar answered Oct 14 '22 14:10

Johnride