5

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?

Panda
  • 6,955
  • 6
  • 40
  • 55
Vidar S. Ramdal
  • 1,164
  • 1
  • 14
  • 38

1 Answers1

3

JavaScript implementation in browsers is asynchronous and single threaded. Of course, it can use multiple worker threads inside (for example, for input/output operations or timers), but your application code is executing on one thread with event loop.

When you connect to the server through WebSocket:

var socket = new WebSocket('ws://localhost:8080');

JavaScript thread starts asynchronous operation for connecting socket and immediately continues to run next code. It can receive events from asynchronous operations only when it returns to the event loop. That means, that your onOpen listener will be always fired, no matter how quickly connection will be established.

I also recommend you to check this question:

How does Asynchronous programming work in a single threaded programming model?

You'll find there a little bit better and extended explanations. Note, that V8 JavaScript engine is used by Node.js and Chromium.

berserkk
  • 987
  • 6
  • 11