Stream Progress of Script

Viewed 27

I'm following a tutorial on streaming data but not having much luck. I've been stuck at the same point since yesterday.

I have a long running php script and would like to show it's progress via the front end. I followed the following tutorial but have now hit a brick wall. https://chrisblackwell.me/server-sent-events-using-laravel-vue/

My code below sends a response of 10 lines (after a 20 seconds wait time), as opposed to a single line every 2 seconds. I am hoping to achieve, that as the php progresses I can display a percentage on the front end.

PHP:

$x = 1;
$response = new StreamedResponse(function() use($x) {
  while ($x <= 10) {
    echo 'data: '.json_encode(['progress' => $x).
    "\n\n";
    ob_flush();
    flush();
    usleep(200000);
    $x++;
  }
});
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('X-Accel-Buffering', 'no');
$response->headers->set('Cache-Control', 'no-cache');
return $response;

JavaScript:

let es = new EventSource('http://awesomestockdata.com/feed');

  es.addEventListener('message', event => {
    let data = JSON.parse(event.data);
    this.stockData = data.stockData;
  }, false);
0 Answers
Related