PHP Server-Sent Events, server side loop

时间:2016-08-31 17:13:20

标签: javascript php html server-sent-events

Info on how to implement Server-Sent Events work:

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

http://www.html5rocks.com/en/tutorials/eventsource/basics/?redirect_from_locale=es

I have implemented a Server-Sent Event in my PHP app which works like this:

  1. FrontEnd displaying info from a DB in Server
  2. BackEnd where user can change the values in the DB (simple form with 'Save' button)

Right now I have a Server-Sent Event in FrontEnd that opens a connection with the server. Then the server script (sse.php) runs a loop to check if there has been any changes in the DB. The changes have to show in real-time in FrontEnd.

I don't like the idea of having a loop checking the DB every 1 second running all the time in the Server.

So here comes my question:

Is there a way to detect, inside the loop, when a user clicks on the BackEnd 'Save' Button, so the script will know that a change has been made and then can notify the FrontEnd to reload the info? (This way I will avoid to check the DB every second to check for changes)

What other options do you consider would be good in my case?

FrontEnd

source.addEventListener('message', function(event) {
    location.reload();
}, false);

sse.php (Server side code)

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include('common.php');
/**
 * Constructs the SSE data format and flushes that data to the client.
 *
 * @param string $id Timestamp/id of this connection.
 * @param string $msg Line of text that should be transmitted.
 */
function sendMsg($id , $msg) {
    echo "id: $id" . PHP_EOL;
    echo "data: {\n";
    echo "data: \"msg\": \"$msg\", \n";
    echo "data: \"id\": $id \n";
    echo "data: }\n";
    echo PHP_EOL;
    ob_flush();
    flush();
}
$data_old = get_background_settings();
do {
$data = get_background_settings();
if($data != $data_old){
    sendMsg($data[0]['duration'] , time());
    $data_old = $data;
}
sleep(1);
// If we didn't use a while loop, the browser would essentially do polling
// every ~3seconds. Using the while, we keep the connection open and only  make
// one request.
} while(true);
?>

Thanks a lot!

0 个答案:

没有答案