Why SSE May Be a Better Choice Than WebSocket for Real‑Time Push

The article compares polling, WebSocket, and Server‑Sent Events (SSE) for server‑to‑client real‑time messaging, explains each method’s advantages and drawbacks, shows when to use SSE versus WebSocket, and provides a complete Node.js/Express demo with front‑end code.

IoT Full-Stack Technology
IoT Full-Stack Technology
IoT Full-Stack Technology
Why SSE May Be a Better Choice Than WebSocket for Real‑Time Push

Server‑to‑Client Push Options

Polling

WebSocket

Server‑Sent Events (SSE)

Polling

Polling repeatedly sends HTTP requests from the client to simulate push. Each request incurs a full HTTP handshake (TCP three‑way handshake, four‑way teardown).

Drawbacks

Every request creates a new connection, causing unnecessary overhead.

Client must keep sending requests from page load, which is unfriendly to the browser.

Browser limits concurrent connections per host (e.g., Chrome 6); a long‑running poll occupies one slot.

Long intervals delay data delivery.

WebSocket

WebSocket provides a full‑duplex channel (ws/wss) allowing bidirectional communication. It requires server‑side support for the new protocol.

Compared with SSE, WebSocket is heavier because of its richer feature set and more complex handshake. Browser compatibility for WebSocket is lower than for SSE.

Server‑Sent Events (SSE)

SSE is a one‑way, long‑living HTTP/1.1 connection that lets the server push data to the browser. It cannot be used for client‑to‑server messages.

Key characteristics of a persistent HTTP connection:

Multiple HTTP requests/responses share a single TCP connection, avoiding repeated handshakes.

Reduces server load and improves performance.

Advantages of SSE:

Lightweight protocol with lower complexity than WebSocket.

Uses standard HTTP, so existing servers support it without extra configuration.

Built‑in reconnection support.

Customizable data types.

Internet Explorer does not support SSE; other major browsers have good compatibility.

Comparison

Polling consumes resources and cannot provide true push.

WebSocket offers full duplex communication but requires a new protocol and server support.

SSE provides a simple, lightweight server‑to‑client push over HTTP, preferable when only one‑way communication is needed.

SSE API Basics

Create an SSE connection in JavaScript: var source = new EventSource(url); Connection readyState values:

0 – CONNECTING (connection not yet established or disconnected)

1 – OPEN (connection established, data can be received)

2 – CLOSED (connection closed, will not reconnect)

SSE events: open – fired when the connection opens message – fired when data arrives error – fired on communication errors

Demo: Building an SSE Application

The demo uses a plain HTML page (front‑end) and a Node.js Express server (back‑end).

Front‑end Steps

Create index.html with the code below and open it in a browser.

<!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>
</body>
<script>
function createLi(data){
  var li = document.createElement("li");
  li.innerHTML = String(data.message);
  return li;
}
var source = '';
if (window.EventSource) {
  source = new EventSource('http://localhost:8088/sse/');
} else {
  throw new Error("Current browser does not support SSE");
}
source.onopen = function(event){
  console.log(source.readyState);
  console.log("Long connection opened");
};
source.onmessage = function(event){
  var data = JSON.parse(event.data);
  console.log(data);
  console.log("Received long‑connection data");
  var li = createLi(data);
  document.getElementById("ul").appendChild(li);
};
source.onerror = function(event){
  console.log(source.readyState);
  console.log("Long connection interrupted");
};
</script>
</html>

Back‑end Steps

Create a folder, add index.js with the server code below.

Run the commands:

npm init          // initialize project
npm i express    // install Express
node index       // start the server
const express = require('express');
const app = express();
const port = 8088;

// CORS setup
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('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 the steps launches the server; the browser displays a timestamp list updated every second.

When to Use Each Solution

SSE is ideal for scenarios that only need server‑to‑client updates (e.g., real‑time dashboards, message‑center notifications).

WebSocket is better for bidirectional use cases such as chat applications where the client also sends messages.

Key Differences Between WebSocket and SSE

WebSocket is full‑duplex; SSE is single‑direction (server‑to‑client).

WebSocket requires server support for the ws/wss protocol; SSE runs over standard HTTP and is supported by existing servers.

SSE is lightweight and simpler; WebSocket is heavier and more complex.

SSE includes automatic reconnection; WebSocket needs additional handling for reconnection.

SSE allows custom data types.

Summary

SSE is lighter than WebSocket and is based on HTTP/HTTPS.

WebSocket introduces a new protocol (ws/wss) and is suited for bidirectional communication.

When only server‑to‑client push is required, prefer SSE.

Both SSE and WebSocket have good browser compatibility except that Internet Explorer does not support SSE.

Polling is the least desirable method due to high client resource consumption.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptNode.jsWebSocketHTMLExpressReal-time PushPollingSSE
IoT Full-Stack Technology
Written by

IoT Full-Stack Technology

Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.