admin管理员组

文章数量:1320610

Is it possible to cancel WebSocket connection while trying to establish connection to the server?

Let's say user notified that it is a misspelled host and want to cancel request for establishing connection before onerror has raised like

failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I tried to call close, but this does not cancel request. I even get warning in console:

failed: WebSocket is closed before the connection is established.

Is it possible to cancel WebSocket connection while trying to establish connection to the server?

Let's say user notified that it is a misspelled host and want to cancel request for establishing connection before onerror has raised like

failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I tried to call close, but this does not cancel request. I even get warning in console:

failed: WebSocket is closed before the connection is established.

Share Improve this question edited Oct 12, 2016 at 7:35 cagdas 1,6442 gold badges14 silver badges27 bronze badges asked Oct 12, 2016 at 7:30 MaklaMakla 10.5k18 gold badges81 silver badges155 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Unfortunately, this is not achievable using close(), and seems not possible at all.

Also, unlike XMLHttpRequest, WebSocket have no abort method to achieve this.

The WebSocket specs do not mention any way of doing this, and setting the object to null does not do the trick.

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

Since the two previous answers to this question have been posted the behaviour of close() seems to have changed.

Quoting the mozilla API docs:

The WebSocket.close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.

You could therefore do this:

var ws = new WebSocket('ws://unknownhost.local');
setTimeout(() => {
  if (ws.readyState == WebSocket.CONNECTING) {
    ws.close();
    console.log("Connection cancelled.");
  }
}, 1000);

Which would cancel the connection attempt if the readyState did not switch to OPEN yet.

I tried this, and it seems to work (tested on Firefox).

close() method only terminates the established connections. For your case, you may use assigning your websocket handle to null where you want to stop it.

webSocketHanle = null;

By this assignment, your callbacks will not be activated.

But notice that it is quite fast process to getting response from server.

本文标签: Cancel WebSocket connection when trying to connect (JavaScript)Stack Overflow