尝试连接时取消 WebSocket 连接 (JavaScript) [英] Cancel WebSocket connection when trying to connect (JavaScript)
问题描述
是否可以在尝试与服务器建立连接时取消 WebSocket 连接?
Is it possible to cancel WebSocket connection while trying to establish connection to the server?
假设用户通知它是一个拼写错误的主机,并希望在 onerror 引发之前取消建立连接的请求
Let's say user notified that it is a misspelled host and want to cancel request for establishing connection before onerror has raised like
失败:连接建立错误:net::ERR_CONNECTION_REFUSED
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
我尝试调用 close,但这不会取消请求.我什至在控制台中收到警告:
I tried to call close, but this does not cancel request. I even get warning in console:
failed:在建立连接之前 WebSocket 已关闭.
failed: WebSocket is closed before the connection is established.
推荐答案
不幸的是,这无法使用 close()
实现,而且似乎根本不可能.
Unfortunately, this is not achievable using close()
, and seems not possible at all.
此外,与 XMLHttpRequest 不同,WebSocket 没有abort
方法来实现这一点.
Also, unlike XMLHttpRequest, WebSocket have no abort
method to achieve this.
WebSocket 规范 没有提到这样做的任何方式,并将对象设置为 null
并不能解决问题.
The WebSocket specs do not mention any way of doing this, and setting the object to null
does not do the trick.
以下示例通过将 WebSocket 对象设置为 null
来说明这一点,但仍然收到连接错误消息.
The following example illustrates this by setting the WebSocket object to null
, but still getting connection error message.
var ws = new WebSocket('ws://unknownhost.local');
ws.onopen = function() {
console.log('ohai');
};
ws = null;
console.log(ws);
// > null
// > VM2346:35 WebSocket connection to 'ws://unknownhost.local/' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
这篇关于尝试连接时取消 WebSocket 连接 (JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!