icicleio / http

HTTP component for Icicle
MIT License
61 stars 5 forks source link

How do I stream a response using chunked transfer encoding ? #25

Open henrywood opened 6 years ago

henrywood commented 6 years ago

I was wondering if it is possible to stream a chunked response using icicle.

Could someone please provide a small example of how I would write to the response's output stream line by line.

If I have this generator:

function getFileLines($file, $mode) {

    $f = fopen($file, $mode);

    try {

        while ($line = fgets($f)) {
            yield $line;
        }
    } finally {
            fclose($f);
    }
}

`` then I would like to be able to send each line to the client using chunked transfer encoding

// Create some kind of response stream here ???
$responseStream = ...
$mime = 'application/json';

    $response = new BasicResponse(200, [
                        'Content-Type'                  => $mime,
                        'Connection'                    => 'keep-alive',
                        'Transfer-Encoding'          => 'chunked',
                        'Server'                        => PROD.'/'.WS_VERSION,
                        'Date'                          => gmdate('D, d M Y H:i:s T')
    ], $responseStream);

$responseStream->seek(0);
$pos = 0;

foreach(getFileLines('some/file.txt') as $l) {
           $len = dechex(strlen($l));
           $line = $len."\r\n";
           $line.= $l."\r\n"
           $responseStream->write($line);
           $pos+= strlen($line);  
           $responseStream->seek($pos);    
}

// End the chunked transfer
$responseStream->end("00\r\n\r\n");

How can I achieve this using ICICLEIO ?

Thanks in advance