HTML Server Sent Events

Last Updated:

HTML Server Sent Events

The HTML Server Sent Events allow a web page to receive automatic updates from a server via HTTP connection.

The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C.

Note: We provided PHP and Node.js server-side code to demonstrate the Server Sent Events. Please choose any one of your favorites.

PHP Server-Side Code

The following is the PHP server-side code used for the below examples.

Example

sse.php
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date("d/m/Y H:i:sa"); echo "data:{$time}\n\n"; flush(); ?>

Node.js Server-Side Code

The following is the Node.js server-side code used for the below examples.

Example

sse.js
var express = require("express"); var app = express(); //Start of code for Server Sent Events app.get("/sse", function(req,res){ res.writeHead(200, { 'Connection': 'keep-alive', 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }); setInterval(function(){ res.write('data:'+ new Date()+ '\n\n'); }, 1000); }); //End of code for Server Sent Events app.listen(8000, function(){ console.log("port is listening to 8000"); });

Client-Side Code

The following is your client-side code.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>Live Data From Server</h1> <div id="point"></div> <script> if(typeof(EventSource) !== "undefined"){ var eventSource = new EventSource('sse.php'); var x = document.getElementById("point"); eventSource.onmessage = function(event) { x.innerHTML+= event.data + "<br>"; } } else{ x.innerHTML = "Sorry, your browser does not support server-sent events"; } </script> </body> </html>

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
SSEYesYesYesNoYesYesYesYesYesYesYesYesYes

Share this Page

Meet the Author