How to catch ERR_CONNECTION_REFUSED thrown by browser if server goes down?

五迷三道 提交于 2020-02-26 08:52:48

问题


I think this question is pretty straightforward, but I haven't found an answer yet in the official Socket.io docs.

I have my Socket.io server and client communicating successfully, and when I shut down the server, the client will attempt to reconnect with the server unsuccessfully. This is shown in the Chrome developer's console here:

Is there any way to detect this event in the client-side Javscript and react to it some way? I'm thinking I would display a dialog on the page, such as "Sorry, server is under heavy load", etc.


回答1:


The correct way to handle this, as of Socket 1.x, is to use the Manager object for a given socket. It throws a connect_error event that can be handled as shown:

socket.io.on('connect_error', function(err) {
  // handle server error here
  console.log('Error connecting to server');
});



回答2:


This should work:

var socket = io('http://localhost');
socket.on('connect_error', function(err) {
  // notify user
});



回答3:


As of now and in the past there is no way to "handle" the red messages. You can't hide them.

Reference: https://stackoverflow.com/a/43056626/5563074

You can't hide them but socket.io does have a way to catch them like presented earlier.

socket.on('connect_error', function(e){
   //Do something
   //console.log(e);
});

Docs: https://socket.io/docs/client-api/#Event-%E2%80%98connect-error%E2%80%99



来源:https://stackoverflow.com/questions/24683572/how-to-catch-err-connection-refused-thrown-by-browser-if-server-goes-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!