State machine 으로 보는 lifecycle
WebSocket connection 은 네 상태 사이를 움직여: CONNECTING (handshake 중) → OPEN (frame 흘러) → CLOSING (한쪽이 close 보냈고 다른 쪽 ack 중) → CLOSED (terminal). 브라우저가 WebSocket.readyState 로 0/1/2/3 노출해.
Frame
WebSocket data 는 byte stream 아니라 frame 의 sequence 야. 각 frame 에 작은 header (2-14 byte) 가 붙어: FIN bit (message 의 마지막 frame?), opcode (text, binary, ping, pong, close, continuation), mask bit, payload length. Client → server frame 은 항상 mask 되어있고 (per-frame XOR key), server → client 는 mask 안 됨. 이 masking 은 anti-cache-poisoning 이지 보안 아냐 — encryption 이랑 헷갈리지 마.
Close code
모든 깨끗한 close 에 code 붙어. 1000 은 normal close. 1001 은 'going away' (서버 shutdown, page 이동). 1006 은 'connection 죽었고 close frame 못 받음' 의 특수 abnormal-close code. 4000-4999 는 application-defined — 'session expired', 'kicked from room' 같은 거에 써.