我在 Symfony 中使用 StreamedResponse 实现了服务器发送事件 (SSE)。因此,当事件发生时,会话中会保存一条消息,该消息将通知给用户。
问题是,当执行包含客户端代码的页面时,它会阻止对应用程序的所有 Web 请求,直到 SSE 连接由于最大执行时间而关闭。
服务器端代码:
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;
}
客户端代码:
<script>
var path = '/path';
var source = new EventSource(path);
source.onmessage = function(e) {
// notification html
};
source.onerror = function(e) {
// notification html
};
</script>
我想知道这是否是 SSE 的良好实现,以及如何使 SSE 调用不阻塞请求。
我使用 symfony 2.6 和 Firefox 作为浏览器。
在此先感谢您的帮助。
session_start()
你使用隐式$this->get('session')
将锁定会话的文件(如果默认情况下使用本机文件会话处理程序),直到您使用
$this->get('session')->save()
只有这样文件才会被解锁。尝试使用上面的方法sleep(8);
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)