One HTTP handshake, then one line that stays open: send, see who may talk on that line, close cleanly or get cut. An interactive WebSocket playground: change…
Why it matters
Chat, live notifications, shared cursors, multiplayer games: all need a server that can speak first. Knowing readyState and how a connection ends keeps you from sending too early, tells a clean close from a cut, and lets you reconnect properly.
The key idea
One HTTP handshake, then one line that stays open
Common mistakes
send() right after new WebSocket() Still CONNECTING (0), not OPEN: send() throws an InvalidStateError. Send inside onopen, or queue it until readyState === 1.
Not handling a dropped connection The network can drop any time (code 1006). Set onclose and reconnect with new WebSocket(), with a growing delay (exponential backoff).
Using a WebSocket for plain request and reply If you only fetch data now and then, HTTP (fetch) is simpler and cacheable. A WebSocket is for frequent, two-way data and pushes from the server.
Try it in this playground
Call ws.send() while still CONNECTING Situation 1: a send right after new WebSocket() throws an InvalidStateError. Send inside onopen.
Get news from the gudang without asking While OPEN, the gudang can send any time. Plain HTTP cannot: a server only answers.
Close with ws.close(1000) readyState 2 (CLOSING) first, until the gudang answers close. Then 3, code 1000, wasClean true.
Cut the line onerror, then onclose with 1006 and wasClean false: cut, not closed.