A Detailed Explanation of HTTP-Based Unidirectional Streaming Communication Protocol SSE

Detailed Explanation of SSE (Server-Sent Events)

๐Ÿง  What is SSE?

SSE (Server-Sent Events) is a communication mechanism defined in the HTML5 standard that allows the server to actively push events to the client (browser). Unlike traditional HTTP request-response, SSE is a unidirectional streaming communication protocol based on HTTP.

๐Ÿ“Œ Core Features

Feature Description
Communication Method Unidirectional: Server โ†’ Client
Connection Type Persistent HTTP Long Connection
Data Format Text (MIME type:<span>text/event-stream</span>)
Automatic Reconnection Automatically supported by the browser
Underlying Protocol HTTP/1.1, compatible with HTTP proxies, caching, and authentication
Establishment Method On the client side, using the <span>EventSource</span> object

๐Ÿงฑ Communication Process (Architecture Diagram)

Browser (Client)
โ””โ”€โ”€ Initiates HTTP GET request (Accept: text/event-stream)
    โ†“
Server (maintains connection)
โ””โ”€โ”€ Whenever there is an event, push:
    data: xxx
    id: 1
    event: myEvent
    retry: 3000

[Connection remains open, server continues to send, client continues to receive]

๐Ÿงช Example Explanation

1. Client (JS)

const source = new EventSource('/events');

source.onmessage = (event) =&gt; {
  console.log('Default message:', event.data);
};

source.addEventListener('update', (event) =&gt; {
  console.log('Received update event:', event.data);
});

source.onerror = (err) =&gt; {
  console.error('Connection error', err);
};

2. Server (Node.js Example)

app.get('/events', (req, res) =&gt; {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  res.write('retry: 5000\n'); // Automatic reconnection time
  res.write('event: update\n');
  res.write(`data: Hello, client\n\n`);

  const interval = setInterval(() =&gt; {
    res.write(`data: Current time ${new Date().toISOString()}\n\n`);
  }, 3000);

  req.on('close', () =&gt; {
    clearInterval(interval);
    res.end();
  });
});

๐ŸŽฏ Typical Application Scenarios

Scenario Description
Real-time Notification System Message pushing, task progress reminders
Real-time Monitoring Dashboard Logs, CPU, memory, API status
Data Display Screen Stock/weather/news stream updates
Chat Room (Read-only) Only requires server to broadcast messages
DevTools/Log Monitoring Real-time display of build logs

๐Ÿ“„ SSE Message Format

event: update
id: 12345
retry: 5000
data: Hello
data: World

Field Description

Field Description
<span>data:</span> Message content, can be multiple lines, concatenated by the client into one
<span>event:</span> Event name, used with JS’s <span>addEventListener</span>
<span>id:</span> Message ID, automatically cached by the client for reconnection
<span>retry:</span> Tells the browser the next reconnection time (ms)

๐Ÿงฐ Comparison with WebSocket

Comparison Item SSE WebSocket
Communication Direction Unidirectional (Server โ†’ Client) Bidirectional
Protocol Based on HTTP Uses ws:// or wss:// (non-HTTP)
Complexity of Use Simple (natively supported by the browser) Requires manual management of message format and connection state
Data Format Plain text (<span>text/event-stream</span>)
Automatic Reconnection Natively supported by the browser Needs to be implemented manually
Proxy Support Good (HTTP proxy available) Poor (many HTTP proxies do not support)
Application Scenarios Real-time notifications, log streams Chat, games, collaborative operations, and other frequently interactive scenarios

๐Ÿ“ก Browser Support

Browser Support Status
Chrome โœ…
Firefox โœ…
Safari โœ…
Edge (Chromium) โœ…
Internet Explorer โŒ Not supported
Mobile Browsers โœ… (most modern browsers)

โš ๏ธ Limitations and Considerations

  1. Not supported in IE
  2. Can only push from the server
  3. Limited by HTTP connection count
  4. Not suitable for transmitting large binary data

๐Ÿ” Cross-Origin & Authentication

  • Use CORS for cross-origin support:
Access-Control-Allow-Origin: *
Content-Type: text/event-stream
  • URL Token Example:
new EventSource(`/events?token=abc123`);

๐Ÿ“ฆ Framework and Tool Support

Technology Stack Support Method
Node.js Native, Express, NestJS
Python Flask + <span>flask-sse</span>, Django Channels
Java Spring WebFlux, Servlet Push
Go Native <span>net/http</span>
Rust Actix, Rocket support SSE
Vue/React Wrap <span>EventSource</span> in Hook/Composables
Nginx Can proxy SSE, needs to disable caching, configure <span>proxy_buffering off;</span>

โœ… Summary: Advantages and Application Judgments of SSE

  • โœ… Simple, lightweight, easy to implement and deploy (based on HTTP)
  • โœ… Suitable for real-time monitoring, system notifications, data stream updates
  • โŒ Not suitable for scenarios requiring client to send messages or binary transmission
  • โŒ Compatibility issues need to consider IE or enterprise intranet browser situations

Leave a Comment