Mastering Real-Time Web Push: From Polling to WebSocket
This article reviews the evolution of web real‑time push techniques—polling, long‑polling, iframe streaming—and explains why WebSocket offers superior bidirectional communication, lower latency, and reduced bandwidth, while providing practical code examples for each method.
Introduction
Modern web applications such as industrial monitoring, online chat, real‑time pricing, and games require the server to push updates to the browser without the user manually refreshing the page. This article compares past and current real‑time push technologies.
1. Two‑Way Communication
The HTTP protocol is client‑initiated only, making server‑push impossible. Before WebSocket, three approaches were used: polling, long‑polling, and iframe streaming.
1.1 Polling
Clients repeatedly request the server at fixed intervals. This creates many connections, adds HTTP headers to each request, and consumes bandwidth and CPU.
Advantages: Simple to implement, no major changes required.
Disadvantages: High latency if interval is long; excessive requests and server load if interval is short.
<!-- 1.html -->
<div id="clock"></div>
<script>
let clockDiv = document.getElementById('clock');
setInterval(function(){
let xhr = new XMLHttpRequest();
xhr.open('GET','/clock',true);
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
clockDiv.innerHTML = xhr.responseText;
}
};
xhr.send();
},1000);
</script> // server (Node/Express)
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.get('/clock', (req,res)=>{
res.end(new Date().toLocaleString());
});
app.listen(8080);1.2 Long‑Polling
The client sends a request and the server holds the connection until new data is available or a timeout occurs, reducing unnecessary traffic.
Advantages: Better timeliness than plain polling, lower bandwidth usage.
Disadvantages: Server must keep connections open, consuming resources; possible timeout handling.
// client (long‑polling)
let clockDiv = document.getElementById('clock');
function send(){
let xhr = new XMLHttpRequest();
xhr.open('GET','/clock',true);
xhr.timeout = 2000;
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
clockDiv.innerHTML = xhr.responseText;
}
};
xhr.ontimeout = send; // retry on timeout
xhr.send();
}
send(); // server can reuse the same endpoint as polling1.3 Iframe Streaming
A hidden iframe is inserted; its src points to a long‑running endpoint that continuously writes script tags to update the parent page.
<!-- 3.html -->
<div id="clock"></div>
<iframe src="/clock" style="display:none"></iframe> // server (Node/Express)
app.get('/clock',(req,res)=>{
setInterval(()=>{
let date = new Date().toLocaleString();
res.write(`<script>parent.document.getElementById('clock').innerHTML='${date}';</script>`);
},1000);
});2. WebSocket
2.1 What Is WebSocket?
WebSocket is a full‑duplex protocol that runs over a single TCP connection, allowing both client and server to send messages at any time after the handshake.
2.2 Limitations of HTTP
Half‑duplex: data flows only one direction per request.
Server cannot push data proactively.
2.3 WebSocket Features
Bidirectional communication with low latency.
Supports text and binary frames.
Reduced overhead: small handshake and frame headers.
<!-- websocket.html -->
<div id="clock"></div>
<script>
let clockDiv = document.getElementById('clock');
let socket = new WebSocket('ws://localhost:9999');
socket.onopen = function(){
console.log('Client connected');
socket.send('hello');
};
socket.onmessage = function(event){
clockDiv.innerHTML = event.data;
console.log('Received from server', event.data);
};
</script> // websocket.js (Node)
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.listen(3000);
let WebSocketServer = require('ws').Server;
let wsServer = new WebSocketServer({port:9999});
wsServer.on('connection', socket=>{
console.log('Client connected');
socket.on('message', message=>{
console.log('Received from client', message);
socket.send('Server reply: '+message);
});
});3. Comparison of Real‑Time Push Techniques
Polling: Simple but wasteful; high latency and bandwidth.
Long‑Polling: Better latency, still holds server resources.
Iframe Streaming: Real‑time delivery, good compatibility, but adds server load and UI loading indicators.
WebSocket: Ideal for bidirectional, low‑latency scenarios (online games, banking); requires modern browser support.
In summary, WebSocket overcomes the passive nature of HTTP and the latency of earlier push methods, offering superior performance for real‑time web applications, while older techniques remain useful for legacy browser compatibility.
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
