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 attribute specifies the URL address where to send the form-data?
method action name
<form action="script.php" method="post"> ... </form>
Which CSS property can be used to break lines in the middle of words?
word-wrap line-height font-size
#id {
  width: 100px;
  word-wrap: break-word;
}
Which function sorts the elements of an array into alphabetical order, based on the string values?
pop() sort() shift()
var tutorials = ["php", "html", "css", "flash"];
tutorials.sort();
alert(tutorials[0]);          // css
Indicate the function that returns the value of the last element into an array.
current() next() end()
$code =[10=>"Perl", 20=>"PHP", 21=>"Python", 30=>"JavaScript");
$last = end($code);
echo $last;      // JavaScript
Using server-sent events - EventSource

Last accessed pages

  1. PHP MySQL - WHERE and LIKE (29343)
  2. Draw arrow markers with clicks in html element (3862)
  3. HTML Symbol Entities (1255)
  4. Get Mime Type of file or string content in PHP (6088)
  5. Node.js Course (2612)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (73)
  2. Read Excel file data in PHP - PhpExcelReader (21)
  3. PHP Unzipper - Extract Zip, Rar Archives (19)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (15)
  5. SSEP - Site Search Engine PHP-Ajax (15)
Chat
Chat or leave a message for the other users
Full screenInchide