Skip to content

Instantly share code, notes, and snippets.

@YavorK
Forked from Deele/sse.html
Last active November 24, 2022 05:45
Show Gist options
  • Save YavorK/6550183a186c64a91d0bd478b8a44f7c to your computer and use it in GitHub Desktop.
Save YavorK/6550183a186c64a91d0bd478b8a44f7c to your computer and use it in GitHub Desktop.
Server-Sent Events example, Javascript client-side, PHP server-side
<html>
<body>
<div id="result"></div>
<script>
if (typeof(EventSource) !== 'undefined') {
console.info('Starting connection...');
var source = new EventSource('/stream.php');
source.addEventListener('open', function(e) {
console.info('Connection was opened.');
}, false);
source.addEventListener('error', function(e) {
var txt;
switch (event.target.readyState) {
// if reconnecting
case EventSource.CONNECTING:
txt = 'Reconnecting...';
break;
// if error was fatal
case EventSource.CLOSED:
txt = 'Connection failed. Will not retry.';
break;
}
console.error('Connection error: ' + txt);
}, false);
source.addEventListener('message', function(e) {
document.getElementById('result').innerHTML += e.data + '<br>';
console.log(e.data);
}, false);
} else {
alert('Your browser does not support Server-sent events! Please upgrade it!');
console.error('Connection aborted');
}
</script>
</body>
</html>
<?php
set_time_limit(30); // this is the script execution time limit,
// if your script hits the time limit the server will kill it.
// you can set to 0 for no time limit (but still your host (if shared hosting) can enforce a hard max time limit
// try leaving this on 30 secs and see how the JS part in the HTML file will reconnect after the stream.php is killed.
//ob_end_clean();
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//header('Connection: keep-alive');
while (true) {
//echo "retry: 1000" . PHP_EOL;
echo 'id: ' . uniqid() . PHP_EOL;
echo 'data: ' . date("h:i:s", time()) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
sleep(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment