Comprehensive Guide to WebSocket: Principles, Handshake, Client API, and Node.js Server Implementation
This article explains WebSocket fundamentals, the HTTP‑based handshake process, client‑side JavaScript API usage with code examples, and a complete Node.js server implementation including connection handling, data‑frame parsing, message broadcasting, heartbeat maintenance, and browser compatibility considerations.
The author, a front‑end engineer at Qunar, shares a detailed overview of WebSocket, a protocol introduced in HTML5 that enables full‑duplex communication between browsers and servers, making it ideal for real‑time chat, notifications, and many other interactive applications.
What is WebSocket? It establishes a persistent TCP connection that allows both parties to push messages at any time, avoiding the overhead of repeated HTTP requests.
Handshake Process – The client sends an HTTP/HTTPS upgrade request containing headers such as Connection: Upgrade, Upgrade: websocket, Sec-WebSocket-Key, etc. The server validates the key, responds with status 101 and headers like Sec-WebSocket-Accept, completing the protocol switch.
WebSocket Client API – The article provides a table of key properties and event listeners (e.g., url, protocol, readyState, onopen, onmessage, onclose, send, close) and demonstrates basic usage:
var ws = new WebSocket('ws://localhost:9001/', 'app');
ws.onopen = function(e) { ws.send('Hello WebSocket!'); };
ws.onmessage = function(messageEvent) {
var message = JSON.parse(messageEvent.data);
switch (message.type) {
case 'update': console.log('Update context: ' + message.content); break;
case 'add': console.log('Add content: ' + message.content); break;
default: break;
}
};
ws.onclose = function() { console.log('Connection closed'); };
ws.onerror = function(err) { console.error(err); };The ws.readyState transitions from 0 (CONNECTING) to 1 (OPEN), then to 2 (CLOSING) and finally 3 (CLOSED) when ws.close() is called.
Server‑Side Implementation – The server must (1) process the handshake request, (2) parse WebSocket data frames, and (3) distribute messages while maintaining a heartbeat. The article outlines these steps and shows how to compute the Sec-WebSocket-Accept using SHA‑1 and Base64 (e.g., with Node.js crypto module).
Data‑frame structure is explained, covering bits such as FIN, opcode, masked, payload length, and the masking key used by browsers.
For a practical server example, the author uses Koa together with the ws module:
// simplified snippet
const Koa = require('koa');
const http = require('http');
const WebSocket = require('ws');
const app = new Koa();
const server = http.createServer(app.callback());
const wss = new WebSocket.Server({ server });
wss.on('connection', function(ws) {
ws.on('message', function(msg) { broadcast(msg); });
setInterval(() => ws.send(JSON.stringify({ type: 'time', content: Date.now() })), 30000);
});
server.listen(3000);The clients API manages connected sockets, and a custom broadcast method sends incoming messages to all clients, enabling a simple chat room.
Browser Support – Modern browsers (Chrome, Firefox, Edge, Safari) fully support WebSocket; IE10+ also works, while older IE versions may need fallback libraries like Socket.IO.
Relation to SPDY/HTTP‑2 – WebSocket provides full‑duplex communication, whereas SPDY/HTTP‑2 focus on multiplexed request/response and server push. They are complementary, not competing protocols.
Conclusion – Combining the event‑driven model of WebSocket with Node.js’s high‑concurrency makes real‑time features (chat, notifications, live dashboards, collaborative tools, etc.) easy to implement on both front‑end and back‑end, offering a solid foundation for modern interactive web applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
