在 Symfony2 中流式传输响应 [英] Streaming a Response in Symfony2

查看:27
本文介绍了在 Symfony2 中流式传输响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试文档中的这个示例:StreamingSymfony2 中的响应.

I am trying this example from the doc: 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;

}

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

This outputs everything at the same time. Have I done something wrong?

推荐答案

我尝试添加 ob_flush() 并且它似乎有效.这是我的代码:

I tried adding ob_flush() and it seems to be working. Here is my code:

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;
}

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

This returns chunked transfer encoding header with chunked data. Here is output of results:

$ 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/*,但是当你看到网络流时,它实际上是通过发送分块数据来进行流式传输.

If you see this response in browser, it will display "HelloWorldHelloWorld" after about 3 seconds loading as browser will wait until all chunked data is received as Content-Type is text/*, but when you see the network stream, it is actually doing streaming by sending chunked data.

这篇关于在 Symfony2 中流式传输响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆