I am struggling to grasp a certain aspect of the Websockets API.
Typically, the onOpen
event handler is utilized for initiating message sending to the server after ensuring that the socket is opened and ready.
Based on various code examples I have come across in the documentation, this seems to be the standard way of setting up an onOpen
event handler for a Websocket:
1: const socket = new WebSocket('ws://localhost:8080');
2:
3: socket.addEventListener('open', function (event) {
4: socket.send('Hello Server!');
5: });
However, the WebSocket constructor call on line 1 establishes the websocket and attempts to open a connection to the server, before attaching the event handler later on line 3.
So, in instances where the connection is established rapidly, could it happen that the socket
is already open by the time we reach line 3?
This raises the concern of potentially missing the open
event if no event handler was registered at the time of its occurrence.
How can we ensure that the open
event will always be received?