0

When I intentionally shut down a web sockets server the client JavaScript code:

try
{
    self.socket.send('ping');
}
catch(ex)
{
    console.log('exception');
}

writes in Chrome console:

WebSocket is already in CLOSING or CLOSED state.

This exception couldn't be caught by try-catch. How to detect for sure that data could not be sent through web socket? onclose event is not being fired.

Paul
  • 25,812
  • 38
  • 124
  • 247

2 Answers2

1

I reconciled myself to the fact that the error couldn't be caught and implemented a ping-pong solution.

JavaScript sends each n seconds a 'ping' command and server should respond with 'pong'. If more than 5 'pings' were sent without response, reconnect is initiated.

Paul
  • 25,812
  • 38
  • 124
  • 247
1

You can check the readyState.

try
{
  if (self.socket && self.socket.readyState === 1) {
    self.socket.send('ping');
  }
  else {
    throw(new Error("WebSocket is not in OPEN state."));
  }
}
catch(ex)
{
  console.log('exception', ex);
}
Ignacio Lago
  • 2,432
  • 1
  • 27
  • 33