Server‑Sent Events (SSE): Scenarios, Comparison with Polling & WebSocket, and Full Implementation Demo
This article explains the three common server‑to‑client push techniques—polling, WebSocket, and SSE—detailing their principles, advantages, and drawbacks, then provides a step‑by‑step Node/Express and plain‑HTML demo showing how to create and use an SSE connection.
In many web applications the server needs to push data to the client, such as real‑time dashboards, unread‑message notifications, or chat updates. The three typical solutions are polling, WebSocket, and Server‑Sent Events (SSE).
Polling
Polling repeatedly sends HTTP requests from the client to simulate push. It consumes a new TCP connection for each request, occupies a browser’s limited concurrent slots, and cannot guarantee timely data delivery, making it the least efficient option.
WebSocket
WebSocket provides a full‑duplex channel over the ws/wss protocol, allowing bidirectional communication. Its strengths are powerful features and real‑time interaction, but it requires server support for the new protocol and has slightly higher complexity.
Server‑Sent Events (SSE)
SSE is a one‑way, HTTP‑based long‑living connection that lets the server push messages to the browser. It is lightweight, uses the existing HTTP infrastructure, and has lower client overhead, though it is not supported by older IE browsers or mini‑programs.
Comparison
WebSocket: full‑duplex, heavier protocol, needs ws support.
SSE: one‑way, lightweight, works over HTTP, auto‑reconnect.
Polling: pseudo‑push, high request overhead, limited concurrency.
SSE API Overview
Creating a connection: var source = new EventSource(url);
Connection state ( source.readyState ): 0 = CONNECTING, 1 = OPEN, 2 = CLOSED.
Key events:
open – triggered when the connection is established.
message – triggered when data arrives.
error – triggered on communication errors.
Data format must use the text/event-stream MIME type with headers Cache-Control: no-cache and Connection: keep-alive .
Demo Implementation
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') return res.sendStatus(200);
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)}\n\n`);
}, 1000);
});
app.listen(port, () => console.log(`Server started at http://localhost:${port}`));Frontend (plain 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('Browser does not support SSE');
}
source.onopen = () => console.log('Connection opened');
source.onmessage = (e) => {
const msg = JSON.parse(e.data);
console.log('Received:', msg);
document.getElementById('ul').appendChild(createLi(msg));
};
source.onerror = () => console.log('Connection error');
</script>
</body>
</html>Running the two files (installing Express with npm i express and starting the server with node index.js ) launches a working SSE demo that continuously pushes the current time to the browser.
Conclusion
SSE is lighter than WebSocket and works over standard HTTP.
Use SSE when only server‑to‑client push is needed (e.g., dashboards, notifications).
Choose WebSocket for full duplex scenarios such as chat.
Polling should be avoided due to high resource consumption.
IE does not support SSE; mini‑programs also lack support.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.