<?
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
/**
* 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: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
$serverTime = time();
while(1){
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));
sleep(0.99);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SSE test</title>
</head>
<body>
<div id="content"></div>
<script>
var c = document.getElementById('content');
var source = new EventSource('sse.php');
source.addEventListener('message', function(e) {
c.innerHTML = e.data;
}, false);
</script>
</body>
</html>