Skip to content

HTML5 Server-Sent Events (SSE)

Server-Sent Events (SSE) is a web technology that allows servers to push data to clients at any time. It's based on the standard HTTP protocol, providing a lightweight, one-way communication channel from server to client.

This is the opposite of the traditional model where clients must actively request data (polling). SSE is ideal for application scenarios requiring real-time updates from the server, such as:

  • Friend status updates on social networks
  • Stock price data
  • Real-time headlines on news websites
  • Sports score broadcasts

SSE vs. WebSockets

SSE is often compared with WebSockets, as both implement server push functionality, but with key differences:

  • Communication direction: SSE is one-way (server -> client). WebSockets are bidirectional.
  • Protocol: SSE is based on standard HTTP/HTTPS, requiring no special protocol or server implementation. WebSockets use their own ws:// or wss:// protocol.
  • Complexity: SSE is simpler with a lighter API. If your application only needs to receive updates from the server without sending large amounts of data to it, SSE is a simpler choice.
  • Auto-reconnect: SSE has built-in automatic reconnection on disconnect, while WebSockets require manual implementation.

Client Implementation: The EventSource Object

On the client side, receiving SSE is very simple—just create an EventSource object and specify a server-side URL that can send an event stream.

html
<div id="result"></div>

<script>
// Check if browser supports EventSource
if(typeof(EventSource) !== "undefined") {
  // Create a new EventSource object pointing to the server-side event source
  var source = new EventSource("demo_sse.php");

  // Listen for 'message' event, which is the default event type
  source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
  };

  // You can also listen for custom-named events
  source.addEventListener('ping', function(event) {
    console.log('Received a ping:', event.data);
  });

  // Listen for connection open
  source.onopen = function() {
    console.log('Connection to server opened.');
  };

  // Listen for errors
  source.onerror = function() {
    console.log('EventSource failed.');
  };

} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support Server-Sent Events...";
}
</script>
  • new EventSource("URL"): Creates an instance and connects to the server.
  • onmessage: Triggered when receiving messages from the server without a specified event name.
  • addEventListener('eventName', callback): Listens for specific events designated by the server.
  • event.data: Contains the message data sent from the server.

Server-Side Implementation

Server-side implementation must follow a specific format. The server must send a special Content-Type header, and each message in the response body must start with data: and end with two newlines \n\n.

PHP Example (demo_sse.php):

php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
  • Content-Type: text/event-stream: This is the required MIME type for SSE.
  • Cache-Control: no-cache: Ensures the event stream is not cached.
  • data: ...\n\n: This is the standard message format.

The server can keep the connection open and send new data: blocks to the client as needed.

Content is for learning and research only.