WebSockets for Real-Time Features
Published by Brayan K
A WebSocket is a persistent, two-way connection between a browser and a server over a single TCP link, letting both sides send messages to each other instantly — ideal for chat, live updates, and other real-time features.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A connected transport is not an application acknowledgement
The browser WebSocket API exposes a connection with open, message, error and close events. A constructor starts connecting; it does not wait for open. On an open connection, send requests transmission. It does not prove that a server parsed the message, authorized it or committed an application operation.
const transportLog = [], pending = new Map();
// This recording transport tests application bookkeeping; it is not a WebSocket.
const transport = { send: text => transportLog.push(text) };
function submit(id, text) {
pending.set(id, text);
transport.send(JSON.stringify({ type: "message", id, text }));
}
submit("m-1", "Hello");
console.log(transportLog.length, pending.has("m-1"));
// Only an explicit application acknowledgement resolves our pending record.
function acknowledge(id) { return pending.delete(id); }
console.log(acknowledge("m-1"), pending.size);
// ✅ Expected output:
// 1 true
// true 0A connection can disappear after a send and before an acknowledgement. Replaying the operation may duplicate an effect; failing to replay may leave its outcome unknown. A durable message ID and server-side deduplication can form an application contract, but neither is built into WebSocket.send. The checked examples below isolate policy with clearly labelled local doubles; they do not claim a live server connection.
Use readyState and events to respect the connection lifecycle
console.log(WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED);
// ✅ Expected output:
// 0 1 2 3Only send while readyState is OPEN. Calling native send during CONNECTING throws InvalidStateError; in CLOSING or CLOSED it silently discards the data. A normal return therefore does not prove transmission. Treat close as a lifecycle event and inspect its code, reason and wasClean without assuming a clean transport closure means every business operation committed.
function sendIfOpen(socket, text) {
if (socket.readyState !== 1) return false;
socket.send(text); return true;
}
for (const state of [0, 1, 2, 3]) {
const calls = [], socket = { readyState: state, send: text => calls.push(text) };
console.log(sendIfOpen(socket, "hello"), calls.length);
}
// ✅ Expected output:
// false 0
// true 1
// false 0
// false 0This fixture verifies our guard, not the browser’s native send implementation. For a real client, construct a WebSocket for your server’s endpoint, attach event listeners and perform initial sends from the open handler. An HTTPS application should use secure WebSocket transport, and the server must verify its expected origins and authorization. The public browser constructor does not offer arbitrary HTTP request headers.
const socket = new EventTarget(); let seen = 0;
const listener = () => seen++;
socket.addEventListener("message", listener);
socket.dispatchEvent(new Event("message"));
socket.removeEventListener("message", () => seen++);
socket.dispatchEvent(new Event("message"));
socket.removeEventListener("message", listener);
socket.dispatchEvent(new Event("message"));
console.log(seen);
// ✅ Expected output:
// 2Stop reconnect timers and detach old listeners when a component or page leaves. Closing a connection and removing listeners are different actions. JavaScript Memory Management & Garbage Collection owns resource lifetime; Custom Event Emitters & Observer Pattern owns listener identity.
Messages need a protocol beyond valid JSON
function decodePrice(text) {
if (typeof text !== "string" || text.length > 1024) throw new TypeError("message must be bounded text");
const value = JSON.parse(text);
if (value === null || typeof value !== "object" || Array.isArray(value) ||
value.version !== 1 || value.type !== "price" ||
typeof value.symbol !== "string" || !/^[A-Z]{1,5}$/.test(value.symbol) ||
!Number.isSafeInteger(value.pence) || value.pence < 0)
throw new TypeError("message does not match price version 1");
return { symbol: value.symbol, pence: value.pence };
}
console.log(JSON.stringify(decodePrice('{"version":1,"type":"price","symbol":"ABC","pence":125}')));
try { decodePrice('{"version":1,"type":"price","symbol":"ABC","pence":"125"}'); }
catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// {"symbol":"ABC","pence":125}
// TypeError message does not match price version 1A message event’s data can be text or binary data. Choose binaryType deliberately for binary protocols; do not JSON.parse a Blob or assume an ArrayBuffer already contains a JavaScript object. Deep Dive into JSON, Parsing & Serialization owns parsing and schema details. Protocol version, maximum size and unknown message types need explicit behavior.
const encoder = new TextEncoder();
for (const text of ["A", "é", "😀"]) console.log(text.length, encoder.encode(text).byteLength);
// ✅ Expected output:
// 1 1
// 1 2
// 2 4The browser’s bufferedAmount measures bytes queued for outgoing transmission. It is not an application acknowledgement count and does not limit incoming traffic. The classic WebSocket API does not supply automatic backpressure; an application must bound its own queues and decide when to drop, coalesce, pause production or disconnect. A message-count limit alone does not bound memory if messages are arbitrarily large.
Ordered transport does not imply ordered asynchronous completion
const completions = [], resolvers = new Map();
function process(id) {
return new Promise(resolve => resolvers.set(id, resolve))
.then(() => completions.push(id));
}
const first = process("first"), second = process("second");
resolvers.get("second")(); await second;
resolvers.get("first")(); await first;
console.log(completions.join(","));
// ✅ Expected output:
// second,firstWebSocket preserves message order on one connection, but your handlers can launch independent asynchronous work. Serialize work when its effects require order, or attach sequence/version information and apply an explicit stale-result policy. Async/Await Architecture & Best Practices owns asynchronous coordination.
let sequence = 3, needsSnapshot = false;
function accept(next) {
if (needsSnapshot) return "waiting";
if (next <= sequence) return "duplicate";
if (next !== sequence + 1) { needsSnapshot = true; return "gap"; }
sequence = next; return "applied";
}
console.log(accept(4), accept(4), accept(6), accept(5));
console.log(sequence, needsSnapshot);
// ✅ Expected output:
// applied duplicate gap waiting
// 4 trueThis chosen application protocol requires consecutive sequence numbers. Another protocol may permit gaps, snapshots or per-channel cursors. Reconnecting gives a new connection; it does not recover missed messages or restore room membership automatically. Only the server’s resume/snapshot protocol can establish what happened while disconnected.
Reconnect policy needs a budget and an owner
let generation = 0;
function begin() {
const ownGeneration = ++generation;
return value => ownGeneration === generation ? value : "stale";
}
const old = begin(), current = begin();
console.log(old("old message"), current("new message"));
// ✅ Expected output:
// stale new messageUse bounded retries and delays, and stop retrying when the user explicitly disconnects or the application leaves. A background retry loop must not reopen a connection after disposal. Authentication failures and unsupported protocol versions may need user action rather than endless retry. Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns retry budgets and backoff mechanics; WebSocket reconnection still needs its own connection-state policy.
Browser JavaScript does not expose native WebSocket ping/pong frame controls. An application heartbeat is an ordinary message whose meaning and timeout rules you design with the server. Timers can be delayed, especially in background tabs, so a missed local deadline is not proof of a particular network failure.
Guided exercise: keep a queue within its chosen message limit
Complete the literal hints. Reject excess entries before mutation, then remove the oldest queued entry first. This simple exercise counts messages only; the independent brief also counts encoded bytes.
const queue = [], limit = 2;
function enqueue(text) {
if (queue.length >= ___) return false; // 👉 replace ___ with limit
queue.___(text); return true; // 👉 replace ___ with push
}
console.log(enqueue("A"), enqueue("B"), enqueue("C"));
console.log(queue.___(), queue.join(",")); // 👉 replace ___ with shift
// ✅ Expected output:
// true true false
// A BIndependent brief: a bounded outgoing queue
Implement createOutbox(socket, limits). It accepts a WebSocket-like event/send contract and positive safe-integer limits for queued message count and UTF-8 bytes. enqueue accepts strings and checks both limits before mutation. It queues only; flush sends queued strings in order while the socket is OPEN and bufferedAmount plus the next message fits maxBytes. Remove an entry only after send returns without throwing. Return the number submitted to the transport, not delivered to a server.
Listen for open to flush, but do not invent a drain event: the caller may call flush again after checking bufferedAmount. stop detaches that listener, discards this queue and rejects future enqueue calls; it does not close a socket it does not own. Flush after stop returns zero. A native send returning undefined does not acknowledge delivery. If an adapter throws after a partial effect, retrying has an uncertain outcome; application IDs and server policy remain necessary.
function createOutbox(socket, { maxMessages = 3, maxBytes = 128 } = {}) {
if (!socket || typeof socket.send !== "function" ||
typeof socket.addEventListener !== "function" || typeof socket.removeEventListener !== "function")
throw new TypeError("socket must provide the event and send contract");
if (!Number.isSafeInteger(maxMessages) || maxMessages < 1 ||
!Number.isSafeInteger(maxBytes) || maxBytes < 1)
throw new RangeError("queue limits must be positive safe integers");
const encoder = new TextEncoder(), queue = [];
let bytes = 0, stopped = false;
function flush() {
if (stopped) return 0;
let sent = 0;
while (queue.length && socket.readyState === 1) {
const item = queue[0];
if (!Number.isFinite(socket.bufferedAmount) || socket.bufferedAmount < 0 ||
socket.bufferedAmount + item.bytes > maxBytes) break;
socket.send(item.text);
queue.shift(); bytes -= item.bytes; sent++;
}
return sent;
}
const onOpen = () => flush();
socket.addEventListener("open", onOpen);
return Object.freeze({
enqueue(text) {
if (stopped) throw new Error("outbox is stopped");
if (typeof text !== "string") throw new TypeError("message must be text");
const size = encoder.encode(text).byteLength;
if (queue.length >= maxMessages || size > maxBytes - bytes)
throw new RangeError("outbox capacity exceeded");
queue.push({ text, bytes: size }); bytes += size;
return queue.length;
},
flush,
pending: () => ({ messages: queue.length, bytes }),
stop() {
if (stopped) return;
stopped = true; socket.removeEventListener("open", onOpen);
queue.length = 0; bytes = 0;
}
});
}
function recordingSocket(state = 0) {
const target = new EventTarget(), sent = [];
return Object.assign(target, {
readyState: state, bufferedAmount: 0, sent,
send(text) { sent.push(text); this.bufferedAmount += new TextEncoder().encode(text).byteLength; }
});
}
const socket = recordingSocket(), queue = createOutbox(socket, { maxMessages: 3, maxBytes: 4 });
queue.enqueue("é"); queue.enqueue("AB");
console.log(JSON.stringify(queue.pending()), queue.flush());
try { queue.enqueue("C"); }
catch (error) { console.log(error.name, error.message); }
socket.readyState = 1; socket.dispatchEvent(new Event("open"));
console.log(socket.sent.join("|"), JSON.stringify(queue.pending()));
queue.enqueue("C");
console.log(queue.flush(), queue.pending().messages);
socket.bufferedAmount = 0;
console.log(queue.flush(), socket.sent.join("|"));
queue.stop(); queue.stop();
try { queue.enqueue("D"); }
catch (error) { console.log(error.message); }
console.log(queue.flush(), JSON.stringify(queue.pending()));
// ✅ Expected output:
// {"messages":2,"bytes":4} 0
// RangeError outbox capacity exceeded
// é|AB {"messages":0,"bytes":0}
// 0 1
// 1 é|AB|C
// outbox is stopped
// 0 {"messages":0,"bytes":0}Reference notes
The WebSocket client guide covers connection events and page lifecycle. The send reference describes queueing and state errors, and the WebSocket reference documents the lack of automatic backpressure. These offline checks do not verify authentication, a handshake, server persistence or real reconnection.
Practice quiz
What does this complete program print? const sent=[],pending=new Set();pending.add("a");sent.push("a");console.log(sent.length,pending.size);
- 1 1
- 1 0
- 0 1
- 0 0
Answer: 1 1. Submitting data to a transport does not remove an application acknowledgement obligation.
What does this complete program print? console.log(WebSocket.CONNECTING===WebSocket.OPEN);
- true
- false
- undefined
- TypeError
Answer: false. Connecting and open are different native states.
What does this complete program print? console.log("😀".length,new TextEncoder().encode("😀").byteLength);
- 1 1
- 2 2
- 2 4
- 4 4
Answer: 2 4. UTF-16 length and UTF-8 byte length measure different things.
What does this complete program print? const q=["A","B"];console.log(q.shift(),q.join(","));
- B A
- A A,B
- B A,B
- A B
Answer: A B. A FIFO queue removes the first queued entry.
What does this complete program print? const t=new EventTarget();let n=0;const f=()=>n++;t.addEventListener("x",f);t.removeEventListener("x",()=>n++);t.dispatchEvent(new Event("x"));console.log(n);
- 1
- 0
- 2
- undefined
Answer: 1. A new function object does not remove the registered listener.
Which conclusion is valid after native WebSocket.send returns normally?
- The server committed the action
- The call alone does not prove that data was transmitted or processed
- The user is authorized
- All prior messages were delivered
Answer: The call alone does not prove that data was transmitted or processed. Closing or closed connections can silently discard the data. Even an open connection needs an application acknowledgement to establish processing.
A new connection opens after a disconnect. What restores missed feed data?
- The open event always replays it
- bufferedAmount returns the missing records
- An explicit server resume or snapshot protocol
- A different event listener name
Answer: An explicit server resume or snapshot protocol. Reconnection alone does not reconstruct missed messages.
What does the bounded outbox fixture verify?
- A real server handshake
- Cross-device delivery
- Permanent message storage
- The queue’s chosen state, ordering and capacity policy
Answer: The queue’s chosen state, ordering and capacity policy. The recording transport is a labelled test double; network and server behavior remain unverified.
Continue this course
- Previous: Client-Side Security Essentials (XSS, CSRF, Sanitisation)
- Next: JavaScript Performance Optimization Techniques — Identify and fix slow JS with profiling, lazy loading, and code splitting
- Quick reference: JavaScript cheat sheet