Sunday 4 August 2013

PHP push message to browser client

Server Sent Events implementation using PHP

In the PHP script, named it server_msg01.php:
1) Content-Type set to text/event-stream
2) using a forever loop to keep on running
3) call set_time_limit(0) to run forever

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}

while(true) {
  set_time_limit(0);
  $serverTime = time();
  sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
  sleep(10);
}
?>

In the html file:
1) In the javascript, create a new EventSource with filename set to the PHP script filename.
2) use div element to display the output

<html>
<head>
<script>
function init() {

    var source;
    if (!!window.EventSource) {
        source = new EventSource('server_msg01.php');
        source.addEventListener('message', function(e) {
            document.getElementById('output').innerHTML += e.data + '<br />';
        }, false);
        source.addEventListener('open', function(e) {
            document.getElementById('output').innerHTML += 'connection opened<br />';
        }, false);
        source.addEventListener('error', function(e) {
 if(document.getElementById("output") != null)
 {
            document.getElementById('output').innerHTML += 'error<br />';
 }
        }, false);
    }
    else {
        alert("Browser doesn't support Server-Sent Events");
    }
}
</script>
</head>
<body onload="init()">

hello world.

<p><div id="output"></div></p>
</body>
</html>

No comments:

Post a Comment