WebSocket Fundamentals and a Simple One‑to‑One Chat Implementation
This article explains the limitations of short and long polling, introduces the WebSocket protocol and its handshake mechanism, and provides complete client‑side and Node.js server code to build a basic real‑time chat application with heartbeat keep‑alive support.
With the growing demand for real‑time updates on the web, traditional polling (where the client repeatedly sends HTTP requests) becomes inefficient, especially for use cases like instant messaging or live pricing. The article first reviews short polling and long‑polling, highlighting their advantages and drawbacks.
Short Polling
In short polling the browser sends an HTTP request every few seconds using XHR or fetch ; the server responds immediately and closes the TCP connection. This approach is simple but generates many unnecessary requests and wastes resources.
setInterval(function(){
fetch(url).then(res => {
// success code
})
}, 3000);Long Polling
Long‑polling keeps the request open until the server has new data or a timeout occurs, reducing the number of empty responses but still consuming server resources while connections are held.
function async(){
fetch(url).then(res => {
async();
// success code
}).catch(() => {
// timeout
async();
})
}WebSocket
WebSocket solves the above problems by upgrading an HTTP connection to a full‑duplex, bidirectional channel, allowing the server to push messages to the client without the client initiating each request.
Handshake Principle
The client initiates the upgrade by sending an HTTP request with an Upgrade: websocket header and a randomly generated Sec-WebSocket-Key . The server replies with a 101 Switching Protocols status, includes Sec-WebSocket-Accept (computed as base64(sha1(key + GUID)) where GUID is the fixed string defined in RFC6455), and confirms the upgrade.
let ws = new WebSocket('ws://localhost:9000');Typical request and response headers are shown in the original article (omitted here for brevity).
Simple One‑to‑One Chat
The following client‑side code creates a WebSocket instance, handles connection events, sends a JSON‑encoded message after opening, and displays incoming messages in the page.
function connectWebsocket() {
ws = new WebSocket('ws://localhost:9000');
// connection opened
ws.onopen = () => {
console.log('连接服务端WebSocket成功');
ws.send(JSON.stringify(msgData));
};
// receive message
ws.onmessage = (msg) => {
let message = JSON.parse(msg.data);
console.log('收到的消息:', message);
elUl.innerHTML += `
小秋:${message.content}
`;
};
ws.onerror = () => {
console.log('连接失败,正在重连...');
connectWebsocket();
};
ws.onclose = () => {
console.log('连接关闭');
};
};
connectWebsocket();The Node.js server uses the ws library, creates an HTTP server with Express, and upgrades it to a WebSocket server. It tracks sessions, forwards messages to the appropriate peer, and logs connection events.
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log(wss.clients.size);
let msgData = JSON.parse(message);
if (msgData.type === 'open') {
ws.sessionId = `${msgData.fromUserId}-${msgData.toUserId}`;
} else {
let sessionId = `${msgData.toUserId}-${msgData.fromUserId}`;
wss.clients.forEach(client => {
if (client.sessionId === sessionId) {
client.send(message);
}
})
}
});
ws.on('close', () => {
console.log('连接关闭');
});
});Both client and server can now exchange messages instantly, as demonstrated by the screenshot in the original article.
Heartbeat Keep‑Alive
To avoid silent disconnections, a periodic ping message (e.g., every 60 seconds) can be sent from the client; the server replies with a pong, keeping the connection alive.
setInterval(() => {
ws.send('这是一条心跳包消息');
}, 60000);Summary
When a WebSocket instance is created, the browser sends an HTTP request containing the Upgrade header; the server responds with status 101 and the connection switches to the WebSocket protocol, establishing a full‑duplex channel. Using the send method and the onmessage event, developers can build real‑time applications such as chat systems with minimal code.
政采云技术
ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.
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.