0

I'm trying to implement Server-Sent Events in Laravel. The stream itself works fine but blocks all other requests to the application until closed. I believe this is related to PHP's session blocking and have researched solutions in similar issues using session_write_close() (or $this->get('session')->save() for Symphony). If this is the case how do I unlock the session's file in Laravel?

Server-side code:

    public function getDataStream(Request $request) {
        $response = new StreamedResponse(
            function () {
                while (true) {
                    echo 'data: {"time": "' . date(DATE_ISO8601) . '"}\n\n';
                    ob_flush();
                    flush();
                    if (connection_aborted()) break;
                    usleep(500000);
                }
            }
        );
        $response->headers->set('Content-Type', 'text/event-stream');
        $response->headers->set('X-Accel-Buffering', 'no');
        $response->headers->set('Connection', 'keep-alive');
        $response->headers->set('Cache-Control', 'no-cache');
        return $response;
    }

Client-side code:

const es = new EventSource('/stream');
es.onmessage = event => {
    console.log('event', event.data)
};
es.onerror = event => {
    console.log('Error: connection closed');
};
knho
  • 19
  • 1
  • 3

0 Answers0