Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible that a Javascript WebSocket could connect before the `open` event listener is added, so you would then miss the event?

Tags:

websocket

This seems to be the canonical way to open a browser-side websocket and then wait for the open event...

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', (event) => {
  socket.send('Hello Server!');
});

According to the standard...

socket = new WebSocket(url [, protocols ])

   Creates a new WebSocket object, immediately establishing the associated WebSocket connection.

If the new immediately starts establishing the connection, is it possible on a very fast link (like, say, to localhost?) that the connection could be established and the open event fired before the line adding the listener is reached? And then the event would be missed?

like image 926
bigjosh Avatar asked Nov 02 '25 07:11

bigjosh


1 Answers

Per a note in section 4 of the WebSockets Standard:

Since the algorithm above is queued as a task, there is no race condition between the WebSocket connection being established and the script setting up an event listener for the open event.

Sometimes implementations fail to adhere to standards, so I tested this locally in Firefox 111.0.1 with the following:

let open_was_caught=false;

const socket=new WebSocket(socket_url);

socket.addEventListener(
   "open",
   ()=>{open_was_caught=true;}
);

if(socket.readyState==WebSocket.OPEN && !open_was_caught)
{
   console.err("Race condition exists!");
}

This test yielded no evidence of the existence of a race condition.

like image 147
Tyler Moore Avatar answered Nov 04 '25 23:11

Tyler Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!