简体   繁体   中英

Cancel WebSocket connection when trying to connect (JavaScript)

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.

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

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM