⚠️ Maintenance. Notice: the site is currently in maintenance mode, so the amount of available material is temporarily limited.
Cheat sheet

WebSocket reference

The numbers and APIs you keep looking up — ready states, close codes, frame opcodes and the client/server surface, on one page.

Справочник по WebSocket

Числа и API, которые постоянно приходится искать — состояния, коды закрытия, опкоды кадров и поверхность клиент/сервер на одной странице.

Ready statesСостояния (readyState)

ValueConstantMeaning
0CONNECTINGHandshake in progress; send() throws.
1OPENReady; you may send and receive.
2CLOSINGClose handshake started.
3CLOSEDClosed, or the connection failed to open.
ЗначениеКонстантаЗначение
0CONNECTINGИдёт рукопожатие; send() бросает исключение.
1OPENГотово; можно отправлять и принимать.
2CLOSINGНачато закрывающее рукопожатие.
3CLOSEDЗакрыто или не удалось открыть.

Common close codesЧастые коды закрытия

CodeNameWhen
1000Normal ClosureClean, intentional close.
1001Going AwayServer shutting down or page navigating away.
1006Abnormal ClosureConnection dropped with no close frame (network loss).
1008Policy ViolationGeneric “you broke a rule” — e.g. auth/token failure.
1009Message Too BigFrame exceeded the receiver's limit.
1011Internal ErrorServer hit an unexpected condition.
1012Service RestartReconnect after a backoff; common during deploys.
3000–4999App-definedYour own codes (e.g. 4401 for re-login).
КодИмяКогда
1000Normal ClosureЧистое преднамеренное закрытие.
1001Going AwayСервер выключается или уход со страницы.
1006Abnormal ClosureРазрыв без close-кадра (потеря сети).
1008Policy ViolationОбщее «нарушение правила» — напр. ошибка авторизации/токена.
1009Message Too BigКадр превысил лимит получателя.
1011Internal ErrorНепредвиденная ситуация на сервере.
1012Service RestartПереподключиться после backoff; типично при выкатке.
3000–4999ПрикладныеВаши коды (напр. 4401 для перелогина).

Frame opcodesОпкоды кадров

OpcodeTypeNotes
0x0ContinuationContinues a fragmented message.
0x1TextUTF-8 payload — arrives as a string.
0x2BinaryArrives as Blob or ArrayBuffer.
0x8CloseControl frame; carries a close code.
0x9PingControl frame; browsers auto-reply with pong.
0xAPongReply to a ping; used for heartbeats.
ОпкодТипЗаметки
0x0ContinuationПродолжение фрагментированного сообщения.
0x1TextUTF-8 — приходит как строка.
0x2BinaryПриходит как Blob или ArrayBuffer.
0x8CloseУправляющий кадр; несёт код закрытия.
0x9PingУправляющий кадр; браузеры авто-отвечают pong.
0xAPongОтвет на ping; используется для heartbeat.

Browser client APIAPI браузерного клиента

client-api.js
const ws = new WebSocket(url, protocols?);

// properties
ws.readyState        // 0..3
ws.bufferedAmount     // bytes queued, not yet sent
ws.protocol           // negotiated subprotocol
ws.binaryType         // "blob" | "arraybuffer"

// methods
ws.send(data);          // string | Blob | ArrayBuffer | TypedArray
ws.close(code?, reason?);

// events
ws.onopen / onmessage / onclose / onerror

Node.js (ws) quick referenceШпаргалка Node.js (ws)

server-api.js
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port, server?, path? });

wss.on("connection", (ws, req) => { … });
wss.clients          // Set of connected sockets

ws.send(data, { binary });
ws.ping() / ws.pong();
ws.terminate();      // hard close, no handshake
ws.on("message" | "close" | "pong" | "error", fn);
Need the “why” behind these? Each row links to a guide in the tutorials. Нужно «почему» за этими цифрами? Каждая тема разобрана в уроках.