Server-Sent Events: Using Server Push in Web Environment
This tutorial demonstrates how you can implement server push messaging.
This feature is supported in mobile applications only.
Warm-up
Become familiar with the Server-Sent Events API basics by learning about:
-
Triggering Server Push Requests
Create an EventSource interface instance.
-
Receiving Server Push Data
Define the data server and the push data receiving event.
Triggering Server Push Requests
To take advantage of the server push feature, you must learn to connect to the server to request push data:
- Create an EventSource interface instance:
<script> var serverPage = "http://165.213.198.151:8080/server_sent_events_server.php"; var eventSource = new EventSource(serverPage);
Note For the server push to work, the serverPage parameter must contain the actual push server URL. - Implement the event handler for the open event:
var log = document.getElementById("log") /* open event */ eventSource.onopen = function(e) { log.innerHTML+= "<p>open: " + new Date() + "</p>"; }; </script>
The open event is triggered repeatedly based on the retry value of the event stream data format, to request push messages from the server.
In the following figure, the open event is fired every 2 seconds.
Figure: Push request event
Source Code
For the complete source code related to this use case, see the following files:
Receiving Server Push Data
To take advantage of the server push feature, you must learn to handle the push data events:
-
Define the data server that the client connects to, according to the event stream interpretation rules.
Set the MIME type to text/event-stream so that the event stream can be sent, and set the header not to be cached.
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); echo "retry: 2000\n\n"; /* Reconnection interval */ echo "data: push time => ". date('r') . "\n\n"; flush(); ?>
-
Create an EventSource interface instance and implement the event handler for the message event:
<script> var serverPage = "http://localhost/server_sent_events_server.php"; var eventSource = new EventSource(serverPage); var log = document.getElementById("log"); /* open event */ eventSource.onopen = function(e) { log.innerHTML+= "<p>-----------------------</p>"; log.innerHTML+= "<p>open: " + new Date() + "</p>"; }; /* message event */ eventSource.onmessage = function(e) { log.innerHTML+= "<p>[push data]: <br>" + e.data + "</p>"; }; </script>
In the following figure, the open event is fired every 2 seconds and the message event shows that push data is received.
Figure: Push message event
Source Code
For the complete source code related to this use case, see the following files: