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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With