WebSockets
WebSockets provide persistent, full-duplex communication channels over TCP. Master connection lifecycle, message protocols, reconnection strategies, heartbeats, and when to use WebSockets versus Server-Sent Events.
How do you use WebSockets in JavaScript?
Create a connection with new WebSocket("wss://example.com/socket"), listen for open, message, close and error events, and send data with socket.send(), usually JSON strings. The connection stays open in both directions, which makes it ideal for chat, live collaboration and multiplayer games. Handle disconnects by reconnecting with a backoff.
const socket = new WebSocket("wss://chat.example.com");
socket.addEventListener("open", () => socket.send(JSON.stringify({ type: "hello" })));
socket.addEventListener("message", (e) => addMessage(JSON.parse(e.data)));
socket.addEventListener("close", () => setTimeout(connect, 2000));readyState Values
Common Close Codes
Common Pitfalls
Interactive Demo
Code Editor
<input id="msg" value="Hello server!">
<button id="send">Send</button>
<ul id="log"></ul>Preview
WebSockets — step by step
WebSocket connection lifecycle
new WebSocket(url) begins the handshake (HTTP Upgrade request). ws.onopen fires when the connection is established. Send messages with ws.send(data) — strings or binary (ArrayBuffer, Blob). Receive with ws.onmessage. ws.onclose fires when either side closes the connection. ws.onerror fires on network errors. The readyState property tracks current state (0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED).
🎯 Quick Check
What is the key advantage of WebSockets over HTTP polling?
WebSockets in JavaScript: summary
Key points
- Always use
wss://in production. - Messages can arrive out of order across reconnects; include IDs or timestamps.
- Socket.IO adds rooms, automatic reconnection and fallbacks on top of WebSockets.
Frequently asked questions
›How do I send JSON over a WebSocket?
socket.send(JSON.stringify(obj)) to send, and JSON.parse(event.data) to read.