从客户端识别套接字服务器是否为 运行

Identify if Socket server is running from client side

当套接字服务器不是运行时,客户端java脚本代码创建一个连接,然后socket.onopen创建一个胎儿错误和java脚本编译器停止执行。

显然无法检测套接字服务器是否 运行。

socket = new WebSocket(socket_serverurl);

在这两种情况下,它 returns,socket.readyState = 0。onerror 也不会触发。

如何检测套接字服务器是否 运行 并优雅地处理此错误?

There is apparently no way to detect if socket server is running or not.

不是特别设计的。根据 WebSocket 接口规范,区分 为什么 连接失败是一种安全风险:

https://websockets.spec.whatwg.org/#feedback-from-the-protocol

User agents must not convey any failure information to scripts in a way that would allow a script to distinguish the following situations:

...

In all of these cases, the WebSocket connection close code would be 1006, as required by WebSocket Protocol. [WSP]

Allowing a script to distinguish these cases would allow a script to probe the user’s local network in preparation for an attack.

但是,正如您在问题中所述:

socket.onopen creates a fetal error

除了你弄错了一个细节。如果连接失败,则不会触发 onopen 事件。 onclose 事件被触发,如 WebSockets 接口规范中所述:

https://websockets.spec.whatwg.org/#eventdef-websocket-open

If the "establish a WebSocket connection" algorithm fails, it triggers the "fail the WebSocket connection" algorithm, which then invokes the "close the WebSocket connection" algorithm, which then establishes that "the WebSocket connection is closed", which fires the close event

这符合 WebSocket 协议规范:

https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4

7.1.4. The WebSocket Connection is Closed

When the underlying TCP connection is closed, it is said that The WebSocket Connection is Closed and that the WebSocket connection is in the CLOSED state. If the TCP connection was closed after the WebSocket closing handshake was completed, the WebSocket connection is said to have been closed cleanly.

If the WebSocket connection could not be established, it is also said that The WebSocket Connection is Closed, but not cleanly.

ReadyState 0 是 CONNECTING。因此,如果您在此状态下收到 onclose 事件(其中 event.wasClean 应为 false,event.code 应为 1006),您就知道连接不成功。

此外,根据接口规范,您还应该得到一个 onerror 事件,尽管您声称自己不是。接口规范很清楚客户在这件事上的责任:

https://websockets.spec.whatwg.org/#feedback-from-the-protocol

When the WebSocket connection is closed, possibly cleanly, the user agent must queue a task to run the following substeps:

  1. Change the ready state to CLOSED (3).
  2. If the user agent was required to fail the WebSocket connection, or if the WebSocket connection was closed" after being flagged as full, fire an event named error at the WebSocket object. [WSP]
  3. Fire an event named close at the WebSocket object, using CloseEvent, with the wasClean attribute initialized to true if the connection closed cleanly and false otherwise, the code attribute initialized to the WebSocket connection close code, and the reason attribute initialized to the result of applying UTF-8 decode without BOM to the WebSocket connection close reason. [WSP]