Skip to content Skip to sidebar Skip to footer

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 f

Solution 1:

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 = newWebSocket('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

Solution 2:

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.

Solution 3:

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 = newWebSocket('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).

Post a Comment for "Cancel Websocket Connection When Trying To Connect (javascript)"