Is WebSocket Still the Best Choice for Real‑Time Push? Explore SSE as a Lightweight Alternative
The article compares polling, WebSocket, and Server‑Sent Events (SSE) for server‑to‑client real‑time messaging, outlines each method’s drawbacks and advantages, and provides step‑by‑step demos showing how to implement SSE with a plain HTML page and a Node‑Express backend.
Real‑time push techniques
Server‑to‑client push is needed in dashboards, notification centers, chat features and similar scenarios. Three common techniques are polling, WebSocket and Server‑Sent Events (SSE).
Polling
Polling repeatedly sends HTTP requests from the client to simulate push. Each request incurs a full TCP handshake, consumes bandwidth, occupies one of the browser’s limited concurrent connections (Chrome caps at six per host), and can introduce latency when the interval is long. Drawbacks include unnecessary handshakes per request, continuous client processing, limited concurrent connections, and delayed data when the polling interval is long.
WebSocket
WebSocket establishes a full‑duplex ws / wss channel, allowing both client and server to send messages at any time. It provides richer functionality but requires support for the new protocol on both client and server and a more complex implementation than plain HTTP.
Server‑Sent Events (SSE)
SSE uses a single long‑lived HTTP/1.1 connection ( text/event-stream) to stream data from server to browser. It is lightweight, reuses the existing HTTP stack, and automatically handles reconnection. It is a one‑way protocol (server‑to‑client) and does not require extra server support beyond standard HTTP. Compatibility: all major browsers except Internet Explorer; mini‑programs also lack SSE support.
Comparison
WebSocket: full‑duplex, stronger features, heavier protocol.
SSE: one‑way (server‑to‑client), lighter, built on HTTP.
WebSocket requires server support for ws / wss; SSE works on any HTTP server.
SSE provides automatic reconnection; WebSocket needs extra handling.
SSE allows custom data types; WebSocket does not impose a format.
When to use
Use SSE when only server‑to‑client push is required (e.g., live dashboards, notification feeds). Use WebSocket when bidirectional communication is needed (e.g., chat applications where the client also sends messages).
Demo: SSE implementation
Front‑end (plain HTML)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSE Demo</title>
</head>
<body>
<ul id="ul"></ul>
<script>
function createLi(data) {
const li = document.createElement('li');
li.innerHTML = String(data.message);
return li;
}
let source = '';
if (window.EventSource) {
source = new EventSource('http://localhost:8088/sse');
} else {
throw new Error('Current browser does not support SSE');
}
source.onopen = function () {
console.log(source.readyState);
console.log('Long connection opened');
};
source.onmessage = function (event) {
console.log(JSON.parse(event.data));
console.log('Received long‑connection message');
const li = createLi(JSON.parse(event.data));
document.getElementById('ul').appendChild(li);
};
source.onerror = function () {
console.log(source.readyState);
console.log('Long connection interrupted');
};
</script>
</body>
</html>Back‑end (Node.js + Express)
const express = require('express');
const app = express();
const port = 8088;
app.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
res.header('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
app.get('/sse', (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
console.log('Entered long‑connection');
setInterval(() => {
const data = { message: `Current time is ${new Date().toLocaleTimeString()}` };
res.write(`data: ${JSON.stringify(data)}
`);
}, 1000);
});
app.listen(port, () => {
console.log(`Server started – http://localhost:${port}`);
});Running steps
Create index.html with the front‑end code.
Create index.js with the back‑end code, run npm init, install Express ( npm i express), then start the server with node index.js.
Open index.html in a browser; the list updates every second with the server time.
SSE API overview
Establish a connection:
var source = new EventSource(url);Connection readyState values:
0 – EventSource.CONNECTING: connection not yet established or reconnecting.
1 – EventSource.OPEN: connection established, data can be received.
2 – EventSource.CLOSED: connection closed and will not reconnect.
Supported events:
open : fired when the connection is opened.
message : fired when a data chunk arrives.
error : fired on communication errors (e.g., connection loss).
Typical response headers for an SSE endpoint:
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-aliveCompatibility
Browser compatibility charts show that SSE is supported by Chrome, Firefox, Safari, Edge and others, but not by Internet Explorer. WebSocket enjoys similarly broad support but requires the ws / wss protocol.
Conclusion
SSE is lighter than WebSocket.
SSE runs over HTTP/HTTPS and requires no extra server support.
WebSocket introduces a new ws / wss protocol.
Use SSE for one‑way server push; use WebSocket for bidirectional communication.
Polling should be avoided except for extreme compatibility cases.
IE does not support SSE; mini‑programs also lack SSE support.
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.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.
