-->

流在Symfony2中一个响应(Streaming a Response in Symfony2)

2019-06-28 05:26发布

我试图从DOC这个例子: 流媒体在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;

}

它输出的同时一切。 难道我做错了什么?

Answer 1:

我尝试添加使用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”的文/ *,但是当你看到网络数据流,它实际上是在做通过发送分块的数据流。



文章来源: Streaming a Response in Symfony2