HTML Server Sent Events

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>

Reminder

Hi Developers, we almost covered 99.5% of HTML Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in HTML.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Meet the Author