How does WebSockets exactly work? Implementing them seemed weird.
First you construct the object with the address, then you define the callbacks like onopen which is called when the connection is opened. Now how does that happen if I told the websocket to connect while constructing it? If the constructor connects in async way, is it guaranteed that my onopen will be called.
To sum it up:
1) When does the websocket decide to connect, when I declare all callbacks?
2) Is send() method async? If so, is there a way to call it sync?
EDIT: I have found out send() is async, there is a bufferedAmount attribute that returns the amount of data that is buffered to be sent. However, the second part of the second question still stands.
I’ve found a good way to explain how this part of an event loop works is this:
Consecutive statements will always be executed before the next event loop iteration happens. This means that you can safely assign event listeners to the
wsobject, because you know that it cannot call them before current iteration completes.As for sending, as you noticed correctly, those values are generally buffered. However, it’s probably a bad idea to send any messages before the
onopenevent is fired, as you’re buffering messages on a not yet opened connection.I hope this answers your question.