Choosing Between SSE, WebSocket, and Polling: When and How to Push Data from Server
This article explains the three main server‑to‑client push techniques—polling, WebSocket, and Server‑Sent Events (SSE)—detailing their principles, advantages, drawbacks, suitable business scenarios, and provides step‑by‑step demo code for implementing SSE with Node.js and plain JavaScript.
Implementation Schemes for Server‑to‑Client Data Push
In everyday development we often need the server to actively push data to the client, such as real‑time dashboards, unread messages in a message center, or chat functionality.
Common Solutions
Polling
WebSocket
SSE (Server‑Sent Events)
Polling Overview
Polling is a pseudo‑push technique where the client repeatedly sends HTTP requests to the server to fetch new data. It incurs unnecessary overhead because each request goes through the full HTTP handshake, consumes a browser’s limited concurrent connection slots, and may not deliver data promptly.
Drawbacks of Polling:
Continuous requests create extra TCP handshakes.
The client must keep sending requests from page load, which is unfriendly to the browser.
Browsers limit concurrent connections per domain (e.g., Chrome limits to 6), and a long‑running poll occupies one slot.
Long‑running polls may fail to fetch data in a timely manner.
WebSocket Overview
WebSocket is a full‑duplex protocol that allows both client and server to send messages independently. It is powerful but introduces a new protocol (ws/wss) that not all browsers support, and its implementation is more complex.
Compatibility:
SSE Overview
SSE is a one‑way communication protocol built on top of HTTP. It establishes a long‑lived HTTP connection that allows the server to push data to the client, but the client cannot send messages back.
Advantages of SSE:
Lightweight compared to WebSocket.
Uses standard HTTP, so existing servers support it without extra configuration.
Lower client resource consumption.
Note: Internet Explorer does not support SSE.
Compatibility:
Differences Between Polling, WebSocket, and SSE
Polling
Used only when both WebSocket and SSE are unavailable; otherwise it is the least preferred method.
WebSocket vs SSE
Both are common for server‑client communication. Neither is universally better; the choice depends on the business scenario.
WebSocket is full‑duplex; SSE is one‑way.
WebSocket requires server support for the ws protocol; SSE runs over standard HTTP.
SSE is lightweight; WebSocket is heavier.
SSE automatically reconnects on disconnection; WebSocket needs extra handling.
SSE allows custom data types.
Business Scenarios
SSE is ideal for one‑way push use cases such as real‑time dashboards and message center notifications, where the client does not need to send data back. WebSocket is suited for bidirectional scenarios like chat applications.
SSE Core API
Creating an SSE Connection
var source = new EventSource(url);SSE Connection States
0 (EventSource.CONNECTING): connection not yet established or disconnected.
1 (EventSource.OPEN): connection open and ready to receive data.
2 (EventSource.CLOSED): connection closed and will not reconnect.
SSE Events
open: triggered when the connection is established. message: triggered when data is received. error: triggered on communication errors or disconnection.
Data Format
Content-Type: text/event-stream // response format
Cache-Control: no-cache // prevent caching
Connection: keep-alive // keep the long‑lived connectionPractical SSE Demo
The demo uses a plain HTML page for the front end and a Node.js Express server for the back end.
Backend (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 SSE 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 at http://localhost:${port}`);
});Frontend (HTML + JavaScript)
<!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('Connection opened');
};
source.onmessage = function (event) {
const data = JSON.parse(event.data);
const li = createLi(data);
document.getElementById('ul').appendChild(li);
};
source.onerror = function () {
console.log('Connection error or closed');
};
</script>
</body>
</html>Run the backend with npm init, npm i express, then node index.js. Open the HTML file in a browser to see live timestamps being pushed from the server.
Summary
SSE is lighter than WebSocket.
SSE works over HTTP/HTTPS, requiring no special server support.
WebSocket introduces a new protocol (ws/wss).
Use SSE when only server‑to‑client push is needed.
Use WebSocket for bidirectional communication such as chat.
Both SSE and WebSocket have good browser compatibility, except IE does not support SSE.
Polling should be avoided due to high resource consumption, though it can be a quick fallback.
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.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.
