12

我正在尝试文档中的这个示例:Streaming a Response in Symfony2

/**
 * @param Request $request
 * @return Response $render
 * @Route("/streamedResponse", name="streamed_response")
 * @Template("AcmeTestBundle::streamedResponse.html.twig")
 */
public function streamedResponseAction(Request $request)
{
    $response = new StreamedResponse();
    $response->setCallback(function () {
        echo 'Hello World';
        flush();
        sleep(3);
        echo 'Hello World';
        flush();
    });

    return $response;

}

这会同时输出所有内容。我做错了什么吗?

4

1 回答 1

21

我尝试添加 ob_flush() ,它似乎正在工作。这是我的代码:

public function streamedAction()
{
    $response = new StreamedResponse();
    $response->setCallback(function () {
        echo 'Hello World';
        ob_flush();
        flush();
        sleep(3);
        echo 'Hello World';
        ob_flush();
        flush();
    });

    return $response;
}

这将返回带有分块数据的分块传输编码标头。这是结果的输出:

$ telnet localhost 80
Trying ::1...
Connected to localhost.
Escape character is '^]'.
GET /app_dev.php/streamed HTTP/1.1
Host: symfony21.localdomain

HTTP/1.1 200 OK
Date: Wed, 12 Sep 2012 05:34:12 GMT
Server: Apache/2.2.17 (Unix) DAV/2 mod_ssl/2.2.17 OpenSSL/0.9.8o
cache-control: no-cache, private
x-debug-token: 50501eda7d437
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

b
Hello World
b
Hello World
0

Connection closed by foreign host.

如果您在浏览器中看到此响应,它将在加载大约 3 秒后显示“HelloWorldHelloWorld”,因为浏览器将等待接收到所有分块数据,因为 Content-Type 是 text/*,但是当您看到网络流时,它实际上是在做通过发送分块数据进行流式传输。

于 2012-09-12T05:40:54.293 回答