Javascript Course


With SSE (Server-Sent Events) the web page can automatically receive data from server without requiring any sending requests.


Receiving events from the server

Server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client.
To receive server-sent event notifications in JavaScript, create an object of the EventSource interface, specifying the URL of the page that sends the messages.

Syntax:
var evsource = new EventSource('sse_file.php');

If the script is hosted on a different domain, define the EventSource with the URI address of the script, and a second argument with an object with the withCredentials property set to true (default is false).
Syntax:
var evsource = new EventSource('//api.example.com/sse_file.php', {withCredentials: true});

Once you've instantiated an event source object, you can begin listening for messages from the server by listening for the message event:
var evsource = new EventSource('sse_file.php');
evsource.addEventListener('message', (ev)=>{
 //getting data from event (ev)
 let data = ev.data;
});

Each message event contains these properties:

Sending event message from the server

The server-side script that sends events needs to respond using the Content-Type: text/event-stream.
Each event 'message' is sent as a block of text with one or more lines, terminated by a pair of newlines.
Syntax (in PHP):
header('Content-Type: text/event-stream');
echo "data:$data\n";
echo "retry:$retry\n";
echo "id=$id \n\n";


The message string must end with two new line characters '\n\n'.
If the string message starts with a colon (:), it is considered a comment, and is ignored.
echo ': Text ignored \n\n';
If a line doesn't contain a colon, the entire line is treated as the field name with an empty value string.

Example server sent events

Here is a simple example that helpls to understand how the server-sent events work with the EventSource object.
- This example displays in a HTML element the time (hour:minutes:seconds) from server side
<h3>Example server sent events with EventSource</h3>
<h4>Server-Time: <span id='ss_time'></span></h4>

<script>
var ss_time = document.getElementById('ss_time');

//if the browser supports EventSource
if(window.EventSource){
 //defines an EventSource object to receive data from sse_ex.php file
 var evsource = new EventSource('javascript/sse_ex.php');

 //detects when it is received message with data from server
 evsource.addEventListener('message', (ev)=>{
 let id = ev.lastEventId; //if you need the event message id

 //gets and adds data in #ss_time
 let data = ev.data;
 ss_time.innerHTML = data;
 });
}
else ss_time.innerHTML ='No server-sent events support.';
</script>
The server-side event stream syntax is simple. First, set the 'Content-Type' header to 'text/event-stream'. Now you can start sending event streams with 'echo' (in PHP).
- The sse_ex.php file contains this code:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); //to prevent caching of event data
header('Access-Control-Allow-Origin: *'); //allows stream access from current domain only

$time = date('h:i:s');
$id = time(); //to set id with current timestamp

//outputs message with a time interval of 1 second (1000 milliseconds
echo "data:$time\n";
echo "retry:1000\n";
echo "id=$id \n\n";

//sends output data to the browser
ob_flush();
flush();

Closing event streams

By default, if the connection between the client and server closes, the connection is reset.
To terminate the connection from the client side, apply the close() method.
var evsource = new EventSource('sse_file.php');
//rest of code..

if(some_condition) evsource.close();

To terminate a stream from the server, respond with a non "text/event-stream" Content-Type, or return an HTTP status other than 200 OK (e.g. 404 Not Found).
header('HTTP/1.0 404 Not Found');
exit();
- It will prevent the browser from re-establishing the connection.

Using custom name for server sent event

The 'message' is the default event name for server-sent events, but it can be specified a custom name on the server-side, by adding the event field in the block of text that is sent to the browser.
Syntax (in PHP):
echo 'event:event_name\n';
echo "data:$data\n";
echo "retry:$retry\n";
echo "id=$id \n\n";

Then, on the client side the JS script can listen for the specified event name.
var evsource = new EventSource('sse_file.php');
evsource.addEventListener('event_name', (ev)=>{
 //getting data from event (ev)
 let data = ev.data;
});
- This code will be called automatically whenever the server sends a message with the event field set to "event_name".

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which meta tag provides a short description of the page?
<meta content="..."> <meta description="..."> <meta http-equiv="...">
<meta name="description" content="70-160 characters that describes the content of the page" />
Which CSS property is used to stop the wrapping effect of the "float"?
clear text-align position
#some_id {
  clear: both;
}
Click on the method which gets an array with all the elements in the document that have a specified tag name.
getElementsByName() getElementById() getElementsByTagName()
var divs = document.getElementsByTagName("div");
var nr_divs = divs.length;
alert(nr_divs);
Indicate the PHP function which returns the number of elements in array.
is_[) count() strlen()
$arr =[7, 8, "abc", 10);
$nri = count($arr);
echo $nri;        // 4
Using server-sent events - EventSource

Last accessed pages

  1. CSS Trapezoid Shape (11313)
  2. Get Attribute (ID, Class, Name, Title, Src) with jQuery (74439)
  3. Node.js Move and Copy file (28290)
  4. AJAX with POST and PHP (18849)
  5. JQZoom Image Magnifier (12975)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (201)
  2. Read Excel file data in PHP - PhpExcelReader (66)
  3. The Mastery of Love (56)
  4. PHP Unzipper - Extract Zip, Rar Archives (51)
  5. Working with MySQL Database (34)
Chat
Chat or leave a message for the other users
Full screenInchide