<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>SSE</title>
<script type="text/javascript">
if (!!window.EventSource) {
var source = new EventSource("sse.php");
} else {
alert("Your browser does not support Server-sent events! Please upgrade it!");
}
source.addEventListener("message", function(e) {
console.log(e.data);
if(e.data){
x = document.getElementById("timer");
x.innerHTML=e.data;
console.log(e.data);
}else{
console.log(e.data);
e.close();
}
}, false);
source.addEventListener("open", function(e) {
console.log("Connection was opened.");
}, false);
source.addEventListener("error", function(e) {
console.log("Error - connection was lost."+e);
}, false);
</script>
</head>
<body>
<div id="timer"></div>
</body>
</html>
My Server Side Code
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
$lastId = 0;
while (true) {
$data =10;
if ($data) {
sendMessage($lastId, $data);
$lastId++;
$data--;
}else{
exit;
}
}
function sendMessage($id, $data) {
//echo "id: $id\n";
echo "$data\n\n";
ob_flush();
flush();
}
?>
What is wrong with my code? Please let me know.
SERVER-SIDE: normally this kind of demo has a sleep between sending each message. What it will do, as it stands, is send 10 packets out in the space of 10ms (or something).
So, the client will get them all at almost the same time, and you will see just the "1" in your timer <div>.
CLIENT-SIDE: It looks okay. It'd be useful to have seen what is being logged to console though. (Probably 10, 10, 9, 9, .., 1, 1, 10, 10, 9, 9, ... repeating forever - see next bit.)
BOTH: I think what will happen when you exit is that the socket will close, the browser will detect that and reconnect. Giving you the same sequence again!
Putting that altogether, change your server-side code main loop to something like:
while (true) {
$data =10;
if ($data) {
sendMessage($lastId, $data);
$lastId++;
$data--;
}else{
sendMessage($lastId, "0");
sleep(1); //Give client time to deal with it.
break;
}
sleep(1); //1 sec between messages
}
I.e. send an explicit "0" to tell the client to disconnect.
Then on the client-side, look out for that explicit close code. (Actually I'd go with "END" or something, as "0" is too easy to evaluated as boolean false!)
source.addEventListener("message", function(e) {
console.log(e.data);
if(e.data==="0")e.close();
else if(e.data){
x = document.getElementById("timer");
x.innerHTML=e.data;
}
//else do nothing
}, false);
Related
I'm working on a one-way messaging system using server-sent events. I have a file (server.html) which sends the contents of a textarea to a PHP file (handler.php).
function sendSubtitle(val) {
var xhr = new XMLHttpRequest();
var url = "handler.php";
var postdata = "s=" + val;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postdata);
//alert(val);
}
This works (alert(val) displays the text in the textarea).
My handler.php code looks like this:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$stringData = $_POST['s'];
echo "data: Data is {$stringData}\n\n";
flush();
And the relevant part of my SSE receiver file (client.html) is as follows:
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("handler.php");
source.onmessage = function(event) {
var textarea = document.getElementById('subtitles');
textarea.value += event.data + "<br>";
textarea.scrollTop = textarea.scrollHeight;
};
} else {
document.getElementById("subtitles").value = "Server-sent events not supported.";
}
The problem is that client.html only displays "data: Data is", so the text from server.html is getting lost somewhere along the way. I imagine it's the PHP code that's falling over, but I can't work out what's wrong. If anyone can help, I'd appreciate it.
EDIT
I chose to use SSE as opposed to websockets as I only need one-way communication: server.html should push the contents of its textarea to client.html whenever it changes. All the examples of SSE that I've looked at (and I've looked at a lot!) send "automatic" time-based data. I haven't seen any that use real-time user input. So perhaps I should clarify my original question and ask, "How can I use SSE to update a DIV (or whatever) in web page B whenever the user types in a textarea in web page A?"
UPDATE
I've narrowed the issue down to the while loop in the PHP file and have therefore asked a new question: Server-side PHP event page not loading when using while loop
Assuming you want to send a value from server.html and a value at client.html will be automatically updated...
You will need to store the new value somewhere because multiple instances of a script do not share variables just like that. This new value can be stored in a file, database or as a session variable, etc.
Steps:
Send new value to phpScript1 with clientScript1.
Store new value with phpScript1.
Connect clientScript2 to phpScript2.
Send stored value to clientScript2 if it is changed.
Getting the new value 'on the fly' means phpScript2 must loop execution and send a message to clientScript2 whenever the value has been changed by clientScript1.
Of course there are more and different approaches to achieve the same results.
Below there's some code from a scratchpad I've used in previous project.
Most parts come from a class (which is in development) so I had to adopt quite a lot of code. Also I've tried to fit it into your existing code.
Hopefully I didn't introduce any errors.
Do note I did not take any validation of your value into account! Also the code isn't debugged or optimized, so it's not ready for production.
Client side (send new value, e.g. your code):
function sendSubtitle(val) {
var xhr = new XMLHttpRequest();
var url = "handler.php";
var postdata = "s=" + val;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postdata);
//alert(val);
}
Server side (store new value):
<?php
session_start();
$_SESSION['s'] = $_POST['s'];
Client side (get new value):
//Check for SSE support at client side.
if (!!window.EventSource) {
var es = new EventSource("SSE_server.php");
} else {
console.log("SSE is not supported by your client");
//You could fallback on XHR requests.
}
//Define eventhandler for opening connection.
es.addEventListener('open', function(e) {
console.log("Connection opened!");
}, false);
//Define evenhandler for failing SSE request.
es.addEventListener('error', function(event) {
/*
* readyState defines the connection status:
* 0 = CONNECTING: Connecting
* 1 = OPEN: Open
* 2 = CLOSED: Closed
*/
if (es.readyState == EventSource.CLOSED) {
// Connection was closed.
} else {
es.close(); //Close to prevent a reconnection.
console.log("EventSource failed.");
}
});
//Define evenhandler for any response recieved.
es.addEventListener('message', function(event) {
console.log('Response recieved: ' + event.data);
}, false);
// Or define a listener for named event: event1
es.addEventListener('event1', function(event) {
var response = JSON.parse(event.data);
var textarea = document.getElementById("subtitles");
textarea.value += response + "<br>";
textarea.scrollTop = textarea.scrollHeight;
});
Server side (send new value):
<?php
$id = 0;
$event = 'event1';
$oldValue = null;
session_start();
//Validate the clients request headers.
if (headers_sent($file, $line)) {
header("HTTP/1.1 400 Bad Request");
exit('Headers already sent in %s at line %d, cannot send data to client correctly.');
}
if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] != 'text/event-stream') {
header("HTTP/1.1 400 Bad Request");
exit('The client does not accept the correct response format.');
}
//Disable time limit
#set_time_limit(0);
//Initialize the output buffer
if(function_exists('apache_setenv')){
#apache_setenv('no-gzip', 1);
}
#ini_set('zlib.output_compression', 0);
#ini_set('implicit_flush', 1);
while (ob_get_level() != 0) {
ob_end_flush();
}
ob_implicit_flush(1);
ob_start();
//Send the proper headers
header('Content-Type: text/event-stream; charset=UTF-8');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no'); // Disables FastCGI Buffering on Nginx
//Record start time
$start = time();
//Keep the script running
while(true){
if((time() - $start) % 300 == 0){
//Send a random message every 300ms to keep the connection alive.
echo ': ' . sha1( mt_rand() ) . "\n\n";
}
//If a new value hasn't been sent yet, set it to default.
session_start();
if (!array_key_exists('s', $_SESSION)) {
$_SESSION['s'] = null;
}
//Check if value has been changed.
if ($oldValue !== $_SESSION['s']) {
//Value is changed
$oldValue = $_SESSION['s'];
echo 'id: ' . $id++ . PHP_EOL; //Id of message
echo 'event: ' . $event . PHP_EOL; //Event Name to trigger the client side eventhandler
echo 'retry: 5000' . PHP_EOL; //Define custom reconnection time. (Default to 3000ms when not specified)
echo 'data: ' . json_encode($_SESSION['s']) . PHP_EOL; //Data to send to client side eventhandler
//Note: When sending html, you might need to encode with flags: JSON_HEX_QUOT | JSON_HEX_TAG
echo PHP_EOL;
//Send Data in the output buffer buffer to client.
#ob_flush();
#flush();
}
//Close session to release the lock
session_write_close();
if ( connection_aborted() ) {
//Connection is aborted at client side.
break;
}
if((time() - $start) > 600) {
//break if the time exceeds the limit of 600ms.
//Client will retry to open the connection and start this script again.
//The limit should be larger than the time needed by the script for a single loop.
break;
}
//Sleep for reducing processor load.
usleep(500000);
}
You called handler.php first time in the server.html and again in client.html. Both are different processes. The variable state won't be retained in the web server. You need to store it somewhere if you want that value in another PHP process. May be you can use sessions or database.
While using sessions you can store the values in two files like:
<?php
//server.php
session_start();
$_SESSION['s'] = $_POST['s'];
And in client.php
<?php
//client.php
session_start();
echo "data: Data is ".$_SESSION['s']."\n\n";
Trying to create a small notification system. When user fills out the profile then his verification status is set to 1 in database and then I would like to show a notification once that "hey you are now verified". Been searching a lot on the internet, but nothing has helped me to reach my goal. If the status is 1 in database I get the Event: verification_ok in the test.php but if it is 0 I get Maximum execution time of 120 seconds exceeded. Also I don't see any response in my client side code.
This is the server side code (test.php).
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Connection: Keep-alive");
require_once $_SERVER['DOCUMENT_ROOT'].'/PHP/scripts/no_session_redirect.php';
$key = true;
$ver = $user_home->runQuery("SELECT verification_status FROM verification WHERE user_id=:user_id");
$ver->execute(array(":user_id"=>$user_id));
$status = $ver->fetch(PDO::FETCH_ASSOC);
while($key){
if($status["verification_status"] == 1){
pushNotification($status["verification_status"]);
$key = false;
}else{
$status["verification_status"];
sleep(10);
}
}
function pushNotification() {
echo "Event: verification_ok\n";
}
And here is the client side code:
$(document).ready(function() {
if (typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
var source = new EventSource("test.php");
source.addEventListener("verification_ok", function(e) {
console.log(e.data);
}, false);
source.addEventListener("open", function(e) {
}, false);
source.addEventListener("error", function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("Error - connection was lost.");
}
}, false);
} else {
// Sorry! No server-sent events support..
}
});
I'm working on a chat log manager - I wanted more control over Thunderbird's chat log archives. There's a synch functionality that basically parses the log files and uploads the messages to a database, zips the logs and stores them in an archive folder.
This process takes a long time to run, and I'd like to display a progress bar. I'm using both jQueryUI and Bootstrap - so a solution that would utilize either of these would be acceptable.
I've tried implementing both of these to no avail so far. The progress bar doesn't show up, and there's no way for me to tell if it's being incremented or not.
I've pasted the code I've got so far. Any help would be appreciated... I have basic knowledge of CSS and my knowledge of javascript is limited at best.
HTML Head
<script>
function UpdatePBar(x){
$( "#progressbar" ).progressbar( "value", x );}
</script>
HTML Body
<div id="progressbar"></div>
Synch process PHP
if(count($this->Contacts) > 0)
{
//GET CONTACTS ALIASES
$result = $this->GetContacts_aliases($folderPath);
if($result) {
echo '<script>UpdatePBar(10)</script>';
flush();
//SYNCH CONTACTS
$result = $this->synch_Contacts();
echo '<script>UpdatePBar(20)</script>';
flush();
if ($result) {
//SYNCH MESSAGES
$result = $this->synch_Messages($folderPath);
echo '<script>UpdatePBar(50)</script>';
flush();
if ($result) {
//SYNCHING SUCCESSFULLY COMPLETED
$log = "Synching of Messages Complete without errors. <br><br>";
$this->log = $this->log . $log;
//UPDATE LAST SYNCHED
$result = $this->UpdateLastSynched();
echo '<script>UpdatePBar(70)</script>';
flush();
if (!$result) {
//Update lastSynched failed
$log = "Updating lastSynched failed! <br><br>";
$this->log .= $log;
} else {
$log = "Updated Last Synched date stamp without errors <br><br>";
$this->log .= $log;
//ARCHIVE LOGS
$result = $this->ArchiveLogs($folderPath);
echo '<script>UpdatePBar(100)</script>';
flush();
if ($result) {
$log = "Archiving of log files successful!<br><br>";
$this->log .= $log;
} else {
$log = "Archiving of log files unsuccessful.<br><br>";
$this->log .= $log;
}
}
} else {
...
Thank you for your time
I think you should do that trough recursive ajax calls.
create a file on php that returns the percentage;
Example: getPercentage.php
<?
//do your stuff
echo $PERCENTAGE;
?>
Then on jquery:
<script>
readPHP();
function readPHP () {
var file="getPercentage.php";
$.ajax({
url: file,
cache: false,
success: function (data , status ) {
percentage=data;
if (percentage < 100)
{
$("#progressbar").progressbar({
value:percentage
})
setTimeout(readPHP(),1000);
}
else
{
$("#progressbar").progressbar({
value:percentage
})
}
}
})
}
</script>
I've implemented long polling mechanism using XMLHttprequest. My problem is that after the browser is closed, the server side process continues to run and doesn't shutdown.
The web server is httpd apache and the process is a php script .
I do want the php script to close after the browser closes .
i discovered that php doesn't discover connection close unless it tries to output data back to the browser .
this is a problem, since it will compromise the objective of minimizing bandwidth usage .
the client side script, uses onreadystatechange to try and read partial data without requiring new XMLHttprequest for each communication .
some browsers will not allow to read partial data until the whole response is finished :
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"></meta>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(NewReq);
var mode = 0;
function NewReq() {
var Req = new XMLHttpRequest();
var url = 'a.php';
if (mode) {
url += '?mode=' + mode;
}
Req.open('GET', url);
Req.onreadystatechange = function(event) {
var handler = ReadyState[this.readyState];
if (typeof handler == 'function') {
handler(this);
}
};
inc_mycookie();
Req.send();
}
var ReadyState = [
//'NotInit', 'ReqRec', 'ConEst'
null , null, null,
partial // 'Proccessing'
,
complete //'Finishied'
];
function partial(Req) { //'Proc'
if (mode == 1) {
return;
}
try {
var strings = Req.response.split(';');
strings.pop();
var data = JSON.parse(strings.pop());
$('#message').text(data);
mode = 2;
}
catch (e) {
$('#message').text(e.message);
mode = 1;
}
return;
}
function complete(Req) {
var last = $('#message').text();
$('#output').text(last);
NewReq();
}
function inc_mycookie() {
var matches = document.cookie.match(/(?:^|;)mine=([^;]+);?/);
if (matches) {
var inc = parseInt(matches[1]) + 1;
document.cookie = 'mine=' + inc;
}
}
</script>
</head>
<body>
<h3> output </h3>
<div id="output"></div>
<h3> partial </h3>
<div id="message"></div>
</body>
</html>
and here is the php script (apache has "php_value output_buffering Off") :
<?php
header('Content-type: application/json');
if (!isset($_COOKIE['mine'])) {
setcookie('mine', 23);
$_COOKIE['mine'] = 23;
}
$mode = isset($_GET['mode']) ? $_GET['mode'] : 1;
print json_encode('test_' . $_COOKIE['mine']) . ';';
if ($mode == 2 ) {
$iter = 8;
while($iter) {
sleep(2);
$iter--;
error_log('a.php:' . $iter);
// if i remove this line, then erro_log will continue to show even when browser is closed
print json_encode('test_' . $_COOKIE['mine'] . '_' . $iter) . ';';
}
}
?>
in the case where browser support partial response, the damage is not too bad .
but if browser require the whole response to finish, then the damage will be a complete compromise of long polling, meaning a repetitive request every 5 seconds .
one possible solution is to add interval :
<?php
$iter = 200;
while($iter) {
sleep(2);
$iter--;
error_log('a.php:' . $iter);
if (update_exist()) {
print json_encode('test_' . $_COOKIE['mine'] . '_' . $iter) . ';';
}
else if (($iter-200)%20 == 0) { // 180, 160, 140 ... 40, 20, 0
print json_encode('check connection : ' . $iter) . ';';
}
}
Even though this is almost 5 years old, consider
XMLHTTPRequest.abort()
The javascript in the question would need to be redesigned in the following ways:
Make Req a global variable, so that
Req.abort() could be called, in (for instance)
window.addEventListener('unload', function() { Req.abort(); })
so that closing the page could cause the client to terminate the connection to the server.
i'm building in php a reservation website with a schedule. I'm looking to have real time updates for my users in a efficient way. I found Ajax but I dont want the client to ask the server about updates but the server to send to the client the updated schedule when somebody edited the schedule.
I found that maybe the HTML5 Server Sent Events is what I need. So I tried a simple test page that retreive update via SSE.
demo.html
<!DOCTYPE html>
<html>
<body>
<h1>SSE Output</h1>
<div id="result"></div>
<h1>Debug Console</h1>
<div id="status"></div>
<script>
//SSE si compatible
if(typeof(EventSource)!=="undefined")
{
var i = 1;
var source=new EventSource("demo_sse.php?ver=2");
//Lorsque le serveur envoie un message
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + " #" + i + "<br />";
i++;
}
//EventListener
source.addEventListener('message', function(e)
{
console.log(e.data);
//document.getElementById("status").innerHTML+= "Message Recevied<br />";
}, false);
source.addEventListener('open', function(e)
{
// Connection was opened.
document.getElementById("status").innerHTML+= "Connection #" + i + " opened<br />";
}, false);
source.addEventListener('error', function(e)
{
if (e.readyState == EventSource.CLOSED)
{
// Connection was closed.
document.getElementById("status").innerHTML+= "Connection closed<br />";
}
}, false);
//Validation de l'origine du serveur
if (event.origin != 'https://mydomain.com')
{
alert('Looks like the Origin of the EventSource (the schedule\'s live update service) wasn\'t coming from our secure server!');
//return;
}
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
demo_see.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$ver = 2;
$time = date("H:i:s");
if ($ver != $_GET["ver"])
{
echo "data: Page updated at: {$time}\n\n";
flush();
}
?>
The problem is that each like 3 seconds there's a connection opened whatever if the version is matching or not so I think it's the client that ask the server and not the server asking the client. What I would like is to keep a open connection between the client and the server so the server can send changes when there's any update made on the schedule.
Any tips would be appreciated!
Thanks
The browser is reconnecting every 3 seconds because your server code isn't keeping the connection open. It sends the time once then ends. Try something more like this:
while (true) {
echo "data: Page updated at: {$time}\n\n";
flush();
sleep(1);
}