我在 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); …Run Code Online (Sandbox Code Playgroud)