# Control Frames and the Closing Handshake — WebSockets & Server-Sent Events

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

> Use ping/pong and close frames correctly and interpret common close codes such as 1000, 1001, 1006 and 1008.

## Closing politely and knowing why

Either side starts a clean shutdown by sending a **close frame** (opcode `0x8`) with a 2-byte **status code** and an optional short UTF-8 reason. The other side replies with its own close frame, and then the TCP connection is closed; the server normally closes TCP first. Codes worth memorising: **1000** normal closure; **1001** going away (server restarting, tab navigating away); **1008** policy violation (for example failed auth); **1009** message too big; **1011** internal server error; **1006** abnormal closure, which is never sent on the wire but reported locally when the connection died without a close frame, such as a crashed process, a dropped mobile network or a proxy timeout. Codes 4000-4999 are free for your application. **Ping** and **pong** control frames check liveness: a ping must be answered with a pong carrying the same data. Browsers answer pings automatically, but the browser JavaScript API cannot send pings itself.

## Reading a close event in the browser

`wasClean` is true only when the close handshake completed. A 1006 with `wasClean: false` is your cue to reconnect.

```js
ws.addEventListener('close', (event) => {
  console.log(event.code, event.reason, event.wasClean);
  if (event.code === 1000) return;          // normal: we or the server chose to close
  if (event.code === 1008) return showLogin(); // policy, e.g. auth expired: do not retry blindly
  scheduleReconnect();                       // 1001, 1006, 1011 and friends: try again
});
```

## 1006 is a symptom, not a diagnosis

Seeing 1006 tells you only that the close handshake did not happen. Check the server logs, proxy idle timeouts, and whether the network dropped. A 1006 that always appears after exactly 60 seconds of silence almost always means a proxy timeout.

## Hanging up a phone call

A clean close is saying "okay, bye" and hearing "bye" back before hanging up. A 1006 is the call dropping in a lift: neither side said goodbye, and you only notice because the line went silent.

**Quiz:** Your client logs close code 1006. What does that mean?

- [ ] The server sent a close frame with code 1006
- [x] The connection ended without a close frame being received
- [ ] The message was too large
- [ ] The server is going away for a restart

*Answer:* The connection ended without a close frame being received. 1006 is reserved for local use: the connection closed abnormally, without the closing handshake. It is never sent in a close frame.
