Frontend Development 7 min read

Common Data Request Methods for Large Screens and Their Implementation with SSE and WebSocket

This article compares HTTP polling, WebSocket, and Server‑Sent Events (SSE) for large‑screen data fetching, explains their advantages and drawbacks, outlines suitable business scenarios, and provides complete front‑end and back‑end code examples for implementing SSE and WebSocket connections.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Common Data Request Methods for Large Screens and Their Implementation with SSE and WebSocket

Common Data Request Methods for Large Screens

1. HTTP Polling

Uses a timer to request data at fixed intervals. Advantages: simple and easy to pass parameters. Disadvantages: data updates are not real‑time and it wastes server resources because requests continue even when data does not change.

2. WebSocket

Establishes a long‑lived connection with the server, allowing the server to push large‑screen data to the client. Advantages: persistent connection, no need for the client to poll, saves server resources, timely data updates, and good browser compatibility (web, H5, mini‑programs). Disadvantages: somewhat heavyweight for simple data queries, requires handling heartbeats, reconnection, etc.

3. Server‑Sent Events (SSE)

Based on HTTP, transforms a single response into a streaming response. Advantages: uses HTTP so it is widely compatible, lightweight, simple, supports automatic reconnection, and allows custom event names. Disadvantages: native EventSource cannot set request headers, so a polyfill (e.g., event-source-polyfill ) is needed, and the server must set the Content‑Type: text/event-stream header.

Differences Between SSE and WebSocket

WebSocket supports bidirectional communication; SSE only allows server‑to‑client messages.

WebSocket is a separate protocol; SSE is built on HTTP.

SSE automatically handles reconnection; WebSocket requires custom reconnection logic.

WebSocket is heavier and more complex; SSE is lighter and easier to use.

Business Scenarios Suitable for WebSocket and SSE

Because SSE is lightweight, simple, and unidirectional, it is ideal for large‑screen data queries such as global statistics, message notifications, and unread counts.

Because WebSocket provides bidirectional communication, it is best suited for features like chat applications.

Frontend Implementation

The front‑end code for SSE is straightforward:

const initSse = () => {
    const source = new EventSource(`/api/wisdom/terminal/stats/change/notify/test`);
    // The event name must match the one sent by the back‑end
    source.addEventListener('stats_change', function (event: any) {
        const types = JSON.parse(event.data).types;
    });
    source.onopen = function () {
        console.log('SSE connection opened');
    };
    source.onerror = function (error: any) {
        console.error('SSE connection error:', error);
    };
    setSseSource(source);
};
// Close the connection
sseSource.close();

Since native SSE cannot set request headers, a polyfill can be used to include authentication tokens:

const source = new EventSourcePolyfill(`/api/wisdom/terminal/stats/change/notify/${companyId}`, {
    headers: {
        Authorization: sessionStorage.get(StorageKey.TOKEN) || storage.get(StorageKey.TOKEN),
        COMPANYID: storage.get(StorageKey.COMPANYID),
        COMPANYTYPE: 1,
        CT: 13,
    }
});
// Event listeners remain the same as native implementation

Backend Implementation

The back‑end must set the response headers Content‑Type: text/event-stream , Cache‑Control: no-cache , and Connection: keep-alive . Each message should be terminated with "\n\n", and individual fields within a message are separated by "\n".

var http = require("http");
http.createServer(function (req, res) {
    var fileName = "." + req.url;
    if (fileName === "./stream") {
        res.writeHead(200, {
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Access-Control-Allow-Origin": '*'
        });
        res.write("retry: 10000\n");
        res.write("event: connecttime\n");
        res.write("data: " + (new Date()) + "\n\n");
        res.write("data: " + (new Date()) + "\n\n");
        interval = setInterval(function () {
            res.write("data: " + (new Date()) + "\n\n");
        }, 1000);
        req.connection.addListener("close", function () {
            clearInterval(interval);
        }, false);
    }
}).listen(8844, "127.0.0.1");

Other Issues Encountered During Development

When using Umi as the development server, the SSE connection was established but no messages appeared in the console, even though the back‑end was sending them. The issue was traced to Umi's proxy configuration; adjusting the proxy settings resolved the problem.

FrontendNode.jsreal-time dataWebSocketSSEHTTP Polling
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login 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.