HTML5 Server-Sent Events

HTML5 Server-Sent Events: To maintain information continuously on your website, you must connect to the web server and it is done by using XML HTTP Requests which has to resent to receive a response for every request. With the help of HTML5 server-side events, you can have a connection that stays longer and receives the updates in a sustained stream.



HTML5 Server-Sent Events

Receiving and Sending SSE

The EventSource object is used to receive and send SSE

Receiving and Sending SSE Example (EventSource object)

<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("sse_demo.php");
source.onmessage = function(event) {
document.getElementById("myresult").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("myresult").innerHTML = "Sorry, server-sent events are not supported in your browser...";
}
</script>

NOTE: Inside the parentheses, a PHP file is known as sse_demo.php which is written in the dynamic programming language to send updates to the browser.

The event source creates an everlasting connection by calling EventSource.close(). This connection helps the browser to receive SSE in text/event-stream media type and the browser cant send data to the server.

Events of Event Source Object in HTML5

EVENT DESCRIPTION
open A connection to the server is enabled
error A connection to the server fails
message A message is collected

HTML5 Server Side

On the server-side, we can use PHP or ASP to send HTML5 updates and the syntax is very easy if we have a little bit of knowledge in those programming languages.

Server Side Example

<?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();
?>

Note: You have to set a Content-Type header to text/event-stream.

Some Tips for HTML5  SSE

These HTML 5 SSE are quite similar to WebSockets, whereas WebSockets is a little bit complicated to use because it requires a unique protocol when SSE depends on HTTP.

The UTF-8 character encoding must be used for the text data stream. The HTML 5 notifications updates may redirect by the HTTP request.