There's a part of the Websockets API I do not understand.
The onOpen
event handler is usually used to start sending messages to the server, since we can't do that before the socket is opened and ready.
According to any code examples I can find (documentation), this is the common way to register an onOpen
eventhandler on a Websocket:
1: const socket = new WebSocket('ws://localhost:8080');
2:
3: socket.addEventListener('open', function (event) {
4: socket.send('Hello Server!');
5: });
But the WebSocket contstructor call (line 1) creates the websocket and attempts to open a connection to the server, while the event handler is attached later (line 3).
So: In a case where the connection is established (very) quickly, is it not possible that socket
is already open when we reach line 3?
In which case we will miss the open
event, since we did not have an event handler registered for it when it happened.
How are we guaranteed to receive the open
event?