How do I know that the server on socket.io is not available, if I enclose my code in a try catch, this construct does not work. The socket.on(disconnect, function(){...}) event socket.on(disconnect, function(){...}) triggered only if the server is turned off while the client is running, but if the server was not started or unavailable before the page was opened, then this event does not fire. How to know that the server is not running from the client?

  • Use the documentation , the socket in addition to disconnect has error , reconnect_error , reconnect_failed events. Depending on the settings, use the appropriate event. - Alex Krass
  • @AlexKrass, this error is still not practiced - max619
  • Those. events socket.on('error', () => {}) , socket.on('reconnect_error', () => {}) , socket.on('reconnect_failed', () => {}) do not work ? - Vasily Barbashev
  • @ Vasily Barbashev, no, they work. But they do not work when the server is initially unavailable. And it only works if you break the connection, when the socket is already connected - max619
  • @ max619 connect_error try - Vasily Barbashev

1 answer 1

There are several events to handle.

In your case, this is connect_error .

Try this code:

 socket.on('connect_error', function() { console.log('Ошибка соединения с сервером. Сервер не доступен!'); });