javascript 如果服务器出现故障,如何捕获浏览器抛出的 ERR_CONNECTION_REFUSED?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24683572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:13:18  来源:igfitidea点击:

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

javascriptnode.jssocket.io

提问by Matt Vukas

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

我认为这个问题很简单,但我还没有在官方的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:

我的 Socket.io 服务器和客户端通信成功,当我关闭服务器时,客户端将尝试重新连接服务器失败。这显示在 Chrome 开发人员的控制台中:

enter image description 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.

有没有办法在客户端 Javscript 中检测到这个事件并以某种方式对其做出反应?我想我会在页面上显示一个对话框,例如“抱歉,服务器负载过重”等。

回答by Matt Vukas

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

从 Socket 1.x 开始,处理此问题的正确方法是使用给定套接字的Manager对象。它抛出一个connect_error事件,可以按如下所示进行处理:

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

回答by glortho

This should work:

这应该有效:

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

回答by Glenn Carver

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

截至目前和过去,没有办法“处理红色消息。你无法隐藏它们。

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

参考:https: //stackoverflow.com/a/43056626/5563074

You can't hidethem but socket.io does have a way to catchthem like presented earlier.

您无法隐藏它们,但 socket.io确实有一种方法可以像前面介绍的那样捕获它们。

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: //socket.io/docs/client-api/#Event-%E2%80%98connect-error%E2%80%99