WebSocket Protocol Cheat Sheet
Quick reference guide for WebSocket Protocol: JS WebSocket API, connection handshake headers, ping/pong, and frames.
Web & Network
websocket
ws
realtime
The WebSocket API provides an advanced technology that opens a two-way interactive communication session between the user's browser and a server.
Browser WebSocket Client API Syntax
typescript
// Open connection (`ws://` or secure `wss://`)
const socket = new WebSocket("wss://echo.websocket.events");
// Event: Connection established
socket.onopen = (event) => {
console.log("WebSocket connection established");
socket.send(JSON.stringify({ type: "ping", time: Date.now() }));
};
// Event: Message received from server
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Server message received:", data);
};
// Event: Error occurred
socket.onerror = (error) => {
console.error("WebSocket error:", error);
};
// Event: Connection closed
socket.onclose = (event) => {
console.log(`Connection closed cleanly: ${event.wasClean}, Code: ${event.code}`);
};
HTTP Handshake Upgrade Headers
To initiate a WebSocket connection, the client sends an HTTP GET request with specific upgrade headers.
http
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server HTTP 101 Response:
http
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
ReadyState Constants
Table
| ReadyState | Constant | Value | Description |
|---|---|---|---|
socket.CONNECTING | 0 | Connection is not yet open | |
socket.OPEN | 1 | Connection is open and ready to communicate | |
socket.CLOSING | 2 | Connection is in the process of closing | |
socket.CLOSED | 3 | Connection is closed or could not be opened |
Common Pitfalls & Tips
[!WARNING] Calling
socket.send()whenreadyState !== WebSocket.OPENthrows anInvalidStateErrorexception! Always checksocket.readyStatebefore sending.
[!TIP] Always implement heartbeat ping/pong timers on long-lived WebSocket connections to prevent proxy load balancers from closing idle connections.