Last active
July 1, 2023 04:16
-
-
Save Deele/ebeb6b9047bab0939e78 to your computer and use it in GitHub Desktop.
Server-Sent Events example, Javascript client-side, PHP server-side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//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