# The Browser WebSocket API — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-ws-browser-api

> Use the WebSocket constructor, events, readyState, send, binaryType and bufferedAmount, and predict the order events fire in.

## Four events and one method

`new WebSocket(url, protocols?)` starts the handshake **asynchronously** and returns immediately with `readyState` `0` (CONNECTING). Later it becomes `1` (OPEN), then `2` (CLOSING) and `3` (CLOSED). You react to four events: `open`, `message` (with `event.data`), `error` and `close` (with `code`, `reason`, `wasClean`). The `error` event carries almost no detail on purpose, so log the following `close` event instead. `send()` accepts strings, `Blob`, `ArrayBuffer` or typed arrays; calling it while still CONNECTING throws an `InvalidStateError`, which is why sending belongs inside `onopen`. Binary messages arrive as `Blob` by default; set `ws.binaryType = 'arraybuffer'` to get `ArrayBuffer`s. `send()` never blocks: data queues in the browser, and `bufferedAmount` reports how many bytes are still waiting, which matters when you upload a lot. Note what is missing: no custom headers, no automatic reconnection and no request/response pairing. Those are your job, or a library's.

## Client, server and handlers

The browser's WebSocket object talks to a server library, which dispatches each incoming message to your handler code. The same picture holds whether the server is Node.js, Python, Go or Java.

![Three connected stages in order: browser WebSocket object, server library, application message handlers.](assets/figures/realtime-web/section-5-map.svg) — Figure 5.1: browser WebSocket -> server library -> message handlers

## Tracing when each handler runs

The server here replies `hi <message>` and then closes with 1000. Watch how the synchronous code finishes before any network event fires.

```js
const ws = new WebSocket('ws://localhost:8090');
ws.onopen = () => ws.send('hello');
ws.onmessage = (e) => console.log('got', e.data);
ws.onclose = (e) => console.log('closed', e.code);
console.log('state', ws.readyState);
```

- Line 1: The constructor only *starts* the handshake; it returns at once.
- Line 2: Assigning `onopen` registers a handler. Nothing is sent yet; the socket is not open.
- Line 4: `onmessage` and `onclose` are registered the same way, still synchronously.
- Line 5: The script reaches this line before the handshake completes, so it prints 0.
- Line 2: The 101 response arrives; the event loop fires `open` and the handler sends `hello`.
- Line 3: The server's reply arrives as a `message` event.
- Line 4: The server sends a close frame with 1000; after the handshake the `close` event fires.

## Do not send before open

`ws.send()` right after `new WebSocket()` throws because the socket is still CONNECTING. Either send inside `open`, or keep an outbox array and flush it when `open` fires; reconnecting clients need that outbox anyway.

**Quiz:** What does `console.log(ws.readyState)` print on the line straight after `new WebSocket(url)`?

- [x] 0, because the handshake has only started
- [ ] 1, because the constructor waits for the handshake
- [ ] 3, because no server has answered
- [ ] It throws until the socket opens

*Answer:* 0, because the handshake has only started. The constructor is non-blocking. The socket stays CONNECTING (0) until the 101 response is processed by the event loop.
