When to Use SSE vs WebSocket: A Practical Guide with Node.js Demo
This article explains server‑to‑client push scenarios, compares polling, WebSocket and Server‑Sent Events (SSE), details SSE APIs and browser compatibility, and provides complete front‑end and back‑end Node.js demos to help you choose the right technology for real‑time data delivery.
Server-to-Client Push Solutions
In many web applications the server needs to push data to the client, such as real‑time dashboards, unread‑message notifications, or chat.
Common Approaches
Polling
WebSocket
Server‑Sent Events (SSE)
Polling Overview
Polling is a pseudo‑push technique where the client repeatedly sends HTTP requests. It incurs connection overhead, consumes client resources, is limited by browser concurrent‑request limits, and may not deliver data promptly.
WebSocket Overview
WebSocket provides full‑duplex communication over a new ws/wss protocol. It is powerful but more complex and requires server support.
Browser compatibility:
SSE Overview
SSE is a one‑way, long‑living HTTP connection that allows the server to push messages. It is lightweight, uses existing HTTP infrastructure, and has lower client overhead.
Note: IE does not support SSE.
Browser compatibility:
SSE API
new EventSource(url) – creates a connection.
source.readyState – 0 (CONNECTING), 1 (OPEN), 2 (CLOSED).
Events: open, message, error.
Data format
Content-Type: text/event-stream // text response format
Cache-Control: no-cache // do not cache
Connection: keep-alive // long‑connection flagDemo
Front‑end HTML page creates an EventSource, handles onopen, onmessage, onerror, and appends received messages to a list.
<!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('当前浏览器不支持SSE');
}
source.onopen = function(){ console.log('长连接打开'); };
source.onmessage = function(event){
const data = JSON.parse(event.data);
const li = createLi(data);
document.getElementById('ul').appendChild(li);
};
source.onerror = function(){ console.log('长连接中断'); };
</script>
</body>
</html>Back‑end Node.js with Express sets the appropriate headers and sends a JSON message every second.
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('进入到长连接了');
setInterval(() => {
const data = { message: `Current time is ${new Date().toLocaleTimeString()}` };
res.write(`data: ${JSON.stringify(data)}
`);
}, 1000);
});
app.listen(port, () => {
console.log(`项目启动成功 - http://localhost:${port}`);
});Conclusion
SSE is lighter than WebSocket.
SSE works over HTTP/HTTPS.
WebSocket uses a new protocol.
Use SSE when only server‑to‑client push is needed.
Use WebSocket for bidirectional communication.
Both have good browser support except IE for SSE.
Polling should be avoided unless absolutely necessary.
Mini‑programs do not support SSE.
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.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.
