Streaming a Response in Symfony2

后端 未结 1 1349
粉色の甜心
粉色の甜心 2020-12-16 00:47

I am trying this example from the doc: Streaming a Response in Symfony2.

/**
 * @param Request $request
 * @return Re         


        
相关标签:
1条回答
  • 2020-12-16 01:10

    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.

    0 讨论(0)
提交回复
热议问题