HTML SSE
HTML Server-Sent Events (SSE)
Section titled “HTML Server-Sent Events (SSE)”Server-Sent Events (SSE) enable a web page to receive automatic updates from a server via an HTTP connection.
Server-Sent Events - One-Way Messaging
Section titled “Server-Sent Events - One-Way Messaging”SSE allows a server to push data to a client (web page) once an initial connection is established. This is different from traditional polling where the client repeatedly asks the server for updates.
With SSE, the updates arrive automatically from the server over a single, long-lived connection.
Common use cases: Real-time notifications (social media feeds, news updates), live data visualization (stock prices, dashboards), status updates (job progress), chat applications (receiving messages).
Browser Support
Section titled “Browser Support”Server-Sent Events are supported by all major modern browsers, including Chrome, Firefox, Safari, Edge, and Opera.
Internet Explorer does not support SSE.
Receiving Server-Sent Event Notifications
Section titled “Receiving Server-Sent Event Notifications”The EventSource JavaScript object is used to receive SSE notifications.
<!-- HTML structure --><div id="result"></div>
<!-- JavaScript --><script> const resultElement = document.getElementById('result');
if (typeof(EventSource) !== 'undefined') { // Create a new EventSource object, specifying the URL of the server endpoint const source = new EventSource('sse_server.php'); // Replace with your server endpoint
// Handle incoming messages (default 'message' event) source.onmessage = function(event) { resultElement.innerHTML += `Data received: ${event.data}<br>`; };
// Optional: Handle the connection opening source.onopen = function(event) { resultElement.innerHTML += 'Connection opened.<br>'; };
// Optional: Handle errors source.onerror = function(event) { resultElement.innerHTML += 'Error occurred.<br>'; // You might want to close the connection or attempt to reconnect here // source.close(); };
} else { resultElement.innerHTML = 'Sorry, your browser does not support Server-Sent Events.'; }</script>Example explained:
- Check if
EventSourceis supported in the browser. - Create a new
EventSourceinstance, providing the URL of the server script that will send events. - Listen for the
onmessageevent: This triggers each time the server sends a message without a specific event name. - The
event.dataproperty contains the message payload from the server. - Optionally, handle
onopenandonerrorevents for connection status and error handling.
Server-Side Code Example
Section titled “Server-Side Code Example”The server needs to send data in a specific format over an HTTP connection.
Key requirements for the server response:
- Set the
Content-Typeheader totext/event-stream. - Set appropriate cache control headers (e.g.,
Cache-Control: no-cache) to prevent intermediate proxies from buffering. - Format messages using
data:,event:,id:, orretry:fields, followed by a newline (\n). - Separate messages with a double newline (
\n\n).
Code in PHP (e.g., sse_server.php):
<?phpheader('Content-Type: text/event-stream');header('Cache-Control: no-cache'); // Recommended to prevent buffering
$time = date('r');echo "data: The server time is: {$time}\n\n"; // Note the double newlineflush(); // Ensure data is sent immediately
// Example of sending multiple events or keeping connection alive/*while(true) { $currentTime = date('r'); echo "data: Current time: {$currentTime}\n\n"; flush(); sleep(5); // Send update every 5 seconds}*/?>Code in Node.js (Conceptual Example):
const http = require('http');
http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' });
setInterval(() => { const time = new Date().toLocaleTimeString(); res.write(`data: The server time is: ${time}\n\n`); }, 1000);
// Send an initial message const time = new Date().toLocaleTimeString(); res.write(`data: The server time is: ${time}\n\n`);
}).listen(3000, () => { console.log('SSE server running on port 3000');});The EventSource Object Events
Section titled “The EventSource Object Events”Besides the default onmessage, you can handle other events:
| Event | Description |
|---|---|
| onopen | Fires when the connection to the server is successfully opened. |
| onmessage | Fires when a message (without a specific event name) is received from the server. |
| onerror | Fires when an error occurs (e.g., connection lost). |
| Custom Events | You can listen for custom events sent from the server using source.addEventListener('eventName', function(event) { ... }); if the server sends messages like event: eventName\ndata: ...\n\n. |