search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Set up the client-side EventSource
Configure the server to send valid SSE responses
Handle reconnection and message IDs
Consider limitations and alternatives
Home Web Front-end H5 Tutorial How to connect to a server using HTML5 Server-Sent Events (SSE)? (Live Data Example)

How to connect to a server using HTML5 Server-Sent Events (SSE)? (Live Data Example)

Dec 21, 2025 am 05:36 AM

HTML5 Server-Sent Events (SSE) enable unidirectional server-to-client real-time updates over standard HTTP using EventSource. Configure client with event listeners for message, custom events, and errors; server must return text/event-stream with proper headers, SSE-formatted lines ending in \n\n, and keep connection open. Supports auto-reconnect, Last-Event-ID resumption, and retry delays, but lacks client-sending, binary support, and is limited to ~6 connections per origin.

How to connect to a server using HTML5 Server-Sent Events (SSE)? (Live Data Example)

To connect to a server using HTML5 Server-Sent Events (SSE), you create an EventSource object in JavaScript that points to an HTTP endpoint returning text/event-stream. Unlike WebSockets, SSE is unidirectional (server → client) and built on standard HTTP — no special protocols or libraries needed on the client side.

Set up the client-side EventSource

Instantiate EventSource with the URL of your SSE endpoint. Handle connection, messages, and errors using event listeners:

  • Use new EventSource("/events") — the browser automatically reconnects on failure (with exponential backoff)
  • Listen for "message" events for generic updates (no event name specified by server)
  • Listen for custom event names like "stock-update" if the server sends event: stock-update
  • Handle "error" to detect persistent failures (e.g., 404, network loss, or server closing stream)

Example:

const source = new EventSource("/live-data");

source.onmessage = function(event) {
  console.log("New data:", event.data);
  document.getElementById("status").textContent = event.data;
};

source.addEventListener("price-change", function(event) {
  const data = JSON.parse(event.data);
  document.getElementById("price").textContent = data.value;
});

source.onerror = function(err) {
  console.error("SSE connection failed", err);
};

Configure the server to send valid SSE responses

Your server must respond with the correct headers and data format. Key requirements:

  • Content-Type header: text/event-stream
  • Cache-Control header: no-cache (or no-store)
  • Response body lines must follow SSE syntax: data: ..., event: ..., id: ..., or retry: ...
  • Each message ends with a blank line (\n\n)
  • Keep the HTTP connection open — do not close it after sending one message

Simple Node.js/Express example:

app.get("/live-data", (req, res) => {
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive"
  });

  // Send initial welcome message
  res.write("data: Welcome to live updates!\n\n");

  const interval = setInterval(() => {
    const now = new Date().toISOString();
    res.write(`data: {"time":"${now}"}\n\n`);
  }, 2000);

  req.on("close", () => {
    clearInterval(interval);
    res.end();
  });
});

Handle reconnection and message IDs

SSE supports automatic reconnection and message resumption via the id field. When the client reconnects, it sends the last seen id in a Last-Event-ID header — your server can use that to resume from where it left off.

  • Include id: 123 before each data: block to assign a unique ID to that message
  • The browser stores the latest ID and sends it on reconnect — your backend should read req.headers["last-event-id"]
  • Use retry: 5000 to set reconnection delay in milliseconds (default is ~3s)

Consider limitations and alternatives

SSE works well for real-time dashboards, notifications, or live metrics — but has constraints:

  • No client-to-server messaging (use regular fetch or WebSockets if bidirectional comms are needed)
  • Most browsers limit ~6 concurrent SSE connections per origin
  • No binary data — everything is UTF-8 text (encode images or files as base64 if required)
  • Firewalls or proxies may buffer or drop long-lived connections — ensure they support streaming

For simple live data feeds, SSE is lightweight, reliable, and natively supported in all modern browsers — no polyfills or extra dependencies needed.

The above is the detailed content of How to connect to a server using HTML5 Server-Sent Events (SSE)? (Live Data Example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)