Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming a Response in Symfony2

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?

like image 807
Mick Avatar asked Sep 12 '12 03:09

Mick


1 Answers

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.

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.

like image 162
mask8 Avatar answered Sep 30 '22 18:09

mask8