Is WebSocket Still the Best Choice for Real‑Time Push? Consider SSE
The article compares polling, WebSocket, and Server‑Sent Events (SSE) for server‑to‑client real‑time messaging, explains each method’s mechanics, advantages and drawbacks, shows browser compatibility, outlines typical business scenarios, and provides a complete Node‑Express demo with code samples.
Introduction
In many daily development scenarios the server needs to push data to the client, such as real‑time dashboards, unread‑message centers, chat functions, and similar use cases.
Implementation Options
Polling
WebSocket
Server‑Sent Events (SSE)
Polling
Polling is a pseudo‑push technique because the client repeatedly sends HTTP requests and the server merely responds. Drawbacks include the overhead of establishing a TCP connection for every request, continuous resource consumption on the client, limited concurrent connections per host (e.g., Chrome allows only six), and potential latency in data delivery.
WebSocket
WebSocket is a full‑duplex protocol (ws/wss) that enables bidirectional communication. Its strengths are powerful functionality and real‑time bidirectional messaging. However, it is a newer protocol, not all browsers support ws, and its implementation is more complex and heavier than SSE.
SSE
SSE is a unidirectional, long‑living HTTP/1.1 connection that allows the server to push data while the client cannot send messages. It is lightweight, uses the existing HTTP stack (no extra server support needed), and automatically reconnects on disconnection. The main limitation is that Internet Explorer does not support SSE. Browser‑compatibility charts are shown in the article.
Comparison
WebSocket is full‑duplex; SSE is one‑way.
WebSocket requires server support for the ws/wss protocol; SSE works over plain HTTP.
SSE is simpler and lighter; WebSocket is comparatively heavier.
SSE provides built‑in reconnection; WebSocket needs additional handling.
SSE allows custom data types.
Business Scenarios
SSE is ideal when only server‑to‑client push is needed, such as real‑time data dashboards or notification centers.
WebSocket is preferable for scenarios that require bidirectional communication, the most typical example being chat applications.
SSE API Overview
Creating a connection: var source = new EventSource(url); Connection state: source.readyState (0 = CONNECTING, 1 = OPEN, 2 = CLOSED).
Events: open (connection established), message (data received), error (communication error).
Data format: Content-Type: text/event-stream, Cache-Control: no-cache, Connection: keep-alive.
Demo: Building an SSE Service with Node Express
Frontend (index.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>Document</title>
</head>
<body>
<ul id="ul"></ul>
<script>
// generate li element
function createLi(data){
let li = document.createElement("li");
li.innerHTML = String(data.message);
return li;
}
// check SSE support
let source = '';
if (window.EventSource) {
source = new EventSource('http://localhost:8088/sse/');
} else {
throw new Error("当前浏览器不支持SSE");
}
// connection opened
source.onopen = function(event){
console.log(source.readyState);
console.log("长连接打开");
};
// receive message
source.onmessage = function(event){
console.log(JSON.parse(event.data));
console.log("收到长连接信息");
let li = createLi(JSON.parse(event.data));
document.getElementById("ul").appendChild(li);
};
// connection error
source.onerror = function(event){
console.log(source.readyState);
console.log("长连接中断");
};
</script>
</body>
</html>Backend (index.js)
const express = require('express'); // 引用框架
const app = express(); // 创建服务
const port = 8088; // 项目启动端口
// 设置跨域访问
app.all("*", function(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(() => {
console.log("正在持续返回数据中");
const data = { message: `Current time is ${new Date().toLocaleTimeString()}` };
res.write(`data: ${JSON.stringify(data)}
`);
}, 1000);
});
app.listen(port, () => {
console.log(`项目启动成功-http://localhost:${port}`);
});Steps: create index.html with the front‑end code, create index.js with the back‑end code, run npm init, install Express with npm i express, then start the server using node index and open the HTML page in a browser.
Result
Conclusion
SSE is lighter than WebSocket.
SSE is based on HTTP/HTTPS.
WebSocket is a newer ws/wss protocol.
Use SSE when only server‑to‑client push is required.
Use WebSocket for bidirectional push.
Both have good browser compatibility (except IE for SSE).
Polling is the least desirable method because it consumes client resources.
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.
IoT Full-Stack Technology
Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.
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.
