Server-Sent Events
I don't know if there is a problem, but I am making a php to javascript feed using Server Sent events instead of ajax. Everything works fine except sleeping on the server side, blocking the event source thread, blocking the webpage thread. I did some pretty simple code for testing and I got the same results.
I'll put the code above.
Server-sent events hang on page flow? its not like ajax that makes asynchronous requests?
Basic question: events sent by the server hang on the stream of code, what I mean is, the page expects the EventSource to keep executing the code, every time eventSouce opens a connection or receives a message. I can see this clearly, when I put in the server side code, my page freezes during sleep, starts for 3 seconds, and then hangs again. When I make an ajax call, the call is asynchronous, so the code keeps running with ajax in the background even if I find myself sleeping on the server side. Hope you can now understand = p
test.php
@set_time_limit(0);
//send the proper header
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if(function_exists('apache_setenv')){
@apache_setenv('no-gzip',1);
}
@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
for($i = 0; $i < ob_get_level(); $i++){
ob_end_flush();
}
ob_implicit_flush(1);
$startedAt = time();
do {
$time = time();
echo "id: $startedAt " . PHP_EOL;
echo "data: {\n";
echo "data: \"msg\": \"$time\", \n";
echo "data: \"id\": $startedAt\n";
echo "data: }\n";
echo PHP_EOL;
//@ob_flush();
@ob_end_flush();
@flush();
usleep(0.5*1000000);
} while(true);
Html
if(!!window.EventSource) {
var source = new EventSource('test.php');
source.addEventListener('open', function(event) {
console.log('open');
}, false);
source.addEventListener('message', function(event) {
var data = JSON.parse(event.data);
console.log(event.data);
},false);
}
source to share