DEV Community

Sadhan Sarker
Sadhan Sarker

Posted on

Event Stream - Server-Send Events

Server-Sent Events is a web API for subscribing to a data stream sent by a server. This opens up a network request to the server so we can stream. Think of it like a Promise that never resolves. Easily implementable using native JavaScript or reactive programming to fetch Event Stream Data.

event-stream

Implementations:

Laravel-Backend Application Source:




// HomeController.php
// import at the begining
use Symfony\Component\HttpFoundation\StreamedResponse;


//-----------------

class HomeController extends Controller
{

    public function getEventStream() {

        $random_string = chr(rand(65, 90)) . chr(rand(65, 90)) . chr(rand(65, 90));
        $data = [
            'message' => $random_string,
            'name' => 'Sadhan Sarker',
            'time' => date('h:i:s'),
            'id' => rand(10, 100),
        ];

        $response = new StreamedResponse();
        $response->setCallback(function () use ($data){

             echo 'data: ' . json_encode($data) . "\n\n";
             //echo "retry: 100\n\n"; // no retry would default to 3 seconds.
             //echo "data: Hello There\n\n";
             ob_flush();
             flush();
             //sleep(10);
             usleep(200000);
        });

        $response->headers->set('Content-Type', 'text/event-stream');
        $response->headers->set('X-Accel-Buffering', 'no');
        $response->headers->set('Cach-Control', 'no-cache');
        $response->send();
    }

}



//-----------------
// Application routes `web.php`

Route::get('/getEventStream', 'HomeController@getEventStream');




Enter fullscreen mode Exit fullscreen mode

JavaScript-Frontend Application



// javascript

let evtSource = new EventSource("/getEventStream", {withCredentials: true});

evtSource.onmessage = function (e) {
let data = JSON.parse(e.data);
console.log(data);
};

Enter fullscreen mode Exit fullscreen mode




Live Project Demo:

Demo Application

Source Code:

Source Code

Top comments (4)

Collapse
 
goopter profile image
goopter

I have a question, in the controller, how can you add an event listener to listen to the event from Laravel application for the record update notification? so when there's an event received, we can trigger the SSE to send change to the frontend

Collapse
 
badpaybad profile image
badpaybad
Collapse
 
mesadhan profile image
Sadhan Sarker

Don't worries Internet Edge will be chromium base very soon, microsoft working on Internet Edge.

 
mesadhan profile image
Sadhan Sarker

yep šŸ¤“