Why use SSE?

Traditional web applications create events which are forwarded to the web server. For example, a simple click on a link demands a fresh page from the server.

The type of events which are running from web browser to the web server might be called user-sent events.

Along with HTML5, WHATWG Web Applications 1.0 presents events which stream from web server to the web browsers, and they are called Server-Sent Events (SSE). Using SSE, we can drive DOM events constantly from our web server to the visitor's browser.

The event running method begins a constant link to the server, giving information to the user when fresh data is accessible, removing the necessary for constant polling.

Server-sent events control how we pass information from the server to the user.

What is Server-Sent Event?

HTML5 server-sent event (SSE) is a modern way for the web pages to conversing with the web server.

It is also feasible with the XMLHttpRequest object that allows JavaScript code to make an appeal to the web server, but it's a one-for-one exchange — that means once the web server delivers its reaction, the interaction is over. XMLHttpRequest object is the heart of every Ajax operations.

However, there are several circumstances where web pages involve a longer-term link to the web server.

A classic example is stock quotes on finance websites where cost updated spontaneously. One More example is a news ticker going on several media websites.

We can produce such things with the HTML5 server-sent events. It allocates a web page to hold an accessible link to a web server, so that the web server can deliver a new reaction spontaneously at any time, there's no requirement to reconnect, and run the similar server script from scratch repeatedly.

Note: Server-Sent Events (SSE) are unidirectional that means information are provided in one way from the server to user. A user is usually a web browser.

Tip: The HTML5's server-sent events feature is endorsed in each main new web browsers like Safari, Opera, Firefox, and Chrome, except Internet Explorer.

Sending Messages with a Server Script

Let's establish a PHP file named "time.php" and type the following script into it. It will easily report the present time of the web server's built-in clock in routine periods.

We will recover this time and update the web page consequently later in this tutorial.

Example: -

The following code explain the sending message with a server.
 <l?php
 // Get the current time on server
 $currentDateTime = date("Y-m-d h:i:s", time());
 // Send it in a message 
 echo "Server Current date & time: " . $currentDateTime. "\n\n";
 flush();
 ?>

Processing Messages in a Web Page

The EventSource object is used to obtain server-sent event messages.

Now let's make an HTML document called "time.htm" and put it in the similar project directory where the "time.php" file is situated.

This HTML document simply accepts the present date and time told by the web server and exhibit it to the client.

Example -

The following example explains the processing message in a webpage.

-

<!DOCTYPE html>
<html lang="en">
 <head>
   <title>Using Server-Sent Events</title>
   <script>
     window.onload = function() {
     var source = new EventSource("time.php");
     source.onmessage = function(event) {
     document.getElementById("result-data")
     .innerHTML += "New date & 
     time received from web server: " + event.data + "<br>";
       }; 
     };
   </script>
 </head>
 <body>
   <div id="result-data">
   <!--Server response will be inserted here--> </div> 
 </body>
</html>  

Output:-

Receiving message with a server script

The EventSource object is used to receive server-sent event messages.

Example -

The following example explains the receiving message with a server script -

<!DOCTYPE html>
<html>
  <body>
    <h1>receive server updates</h1>
    <div id="result"></div>
    <script>
       if(typeof(EventSource) !== "undefined") { 
       var source = new EventSource("time.php");
       source.onmessage = function(event) {
     document.getElementById("result").innerHTML += event.data + "<br>";
       }; 
       } else { 
       document.getElementById("result").innerHTML = "Sorry,
       your browser does not support server-sent events...";
       } 
   </script> 
 </body>
</html> 

Output:-

receive server updates

Explaining Example -

  • Build a new EventSource object, and identify the URL of the page delivering the updates (in this example "time.php")
  • Every time an update is accepted, the onmessage event happens.
  • When an onmessage event happens, placed the accepted information into the element with id="result-data".

The EventSource Object

In the above examples we use the onmessage event to make messages. But additional events are also accessible -

Events Description
onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occurs

SSE Field Names

Each SSE message begins with a fieldname, except for a comment. The entire set of pre-defined field names involve -

  • event: The event type, such as message, or another described by our application.
  • data: The field data itself.
  • retry: An integer value suggesting the re-joining time in case of a disconnect.
  • id: Message id value.

Browser Support

The following browsers and corresponding versions in the table that completely supports the SSE.

API Chrome Edge Firefox Safari Opera
SSE 6.0 Not supported 6.0 5.0 11.5