laravel server sent events
$loopTime = 1; $response = new StreamedResponse(static function () use ($loopTime) { while (true) { $data = [ 'name' => 'Taylor Otwell' ] echo "event: sse\n"; echo "data: " . json_encode($data) . "\n\n"; echo str_pad('', 4096) . "\n"; ob_flush(); flush(); sleep($loopTime); if (connection_aborted()) { break; } } ob_end_flush(); } $response->headers->set('Content-Type', 'text/event-stream'); $response->headers->set('Cache-Control', 'no-cache'); return $response;
Here is what the above code is Doing:
1. We’re creating a new StreamedResponse object.
2. We’re passing a callback function to the StreamedResponse object.
3. The callback function is an infinite loop that will run forever.
4. The callback function will send a message to the client every second.
5. The callback function will break out of the loop if the client disconnects.
6. We’re setting the Content-Type header to text/event-stream.
7. We’re setting the Cache-Control header to no-cache.
8. We’re returning the response.
Now, let’s create a route that will return the response:
Route::get(‘/sse’, function () {
return response()->stream(function () {
while (true) {
$data = [
‘name’ => ‘Taylor Otwell’
];
echo “event: sse\n”;
echo “data: ” . json_encode($data) . “\n\n”;
echo str_pad(”, 4096) . “\n”;
ob_flush();
flush();
sleep(1);
if (connection_aborted()) {
break;
}
}
ob_end_flush();
}, 200, [
‘Content-Type’ => ‘text/event-stream’,
‘Cache-Control’ => ‘no-cache’
]);
});