I did an implementation of Server Sent Event (SSE) with StreamedResponse in Symfony. So when an event occurs a message is saved in the session, this message will be notified to the user. The problem is when the page that contains the client code is executed, it blocks all web requests to the application until the SSE connection is closed due to Maximum execution time.
Server side code:
public function notificationAction() {
$response = new StreamedResponse(function() {
while(true) {
$message = "";
$messagesNotification = $this->get('session')->getFlashBag()->get('message_notification');; // code that search notifications from session
if(count($messagesNotification)>0){
foreach ( $messagesNotification as $messageNotification ) {
$message .= "data: " . messageNotification . PHP_EOL;
}
$message .= PHP_EOL;
echo $message;
ob_flush();
flush();
}
sleep(8);
};
});
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('Cache-Control', 'no-cache');
return $response;
}
Client side code:
<script>
var path = '/path';
var source = new EventSource(path);
source.onmessage = function(e) {
// notification html
};
source.onerror = function(e) {
// notification html
};
</script>
I would like to know if this is a good implementation of SSE, and how to make the SSE call not to block requests.
I'm using symfony 2.6 and Firefox as the browser.
Thanks in advance for your help.