jhe*_*cia 4 symfony server-sent-events
我在 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;
}
Run Code Online (Sandbox Code Playgroud)
客户端代码:
<script>
var path = '/path';
var source = new EventSource(path);
source.onmessage = function(e) {
// notification html
};
source.onerror = function(e) {
// notification html
};
</script>
Run Code Online (Sandbox Code Playgroud)
我想知道这是否是 SSE 的良好实现,以及如何使 SSE 调用不阻止请求。
我使用 symfony 2.6 和 Firefox 作为浏览器。
在此先感谢您的帮助。
session_start()您使用隐式 with$this->get('session')将锁定会话的文件(如果您使用本机文件会话处理程序,默认情况下),直到您使用
$this->get('session')->save()
Run Code Online (Sandbox Code Playgroud)
只有这样文件才会被解锁。尝试在上面使用它sleep(8);。
| 归档时间: |
|
| 查看次数: |
3523 次 |
| 最近记录: |