如果连接保持活着如何读取直到流的结束PHP

Sam*_*msh 12 php http

$f = fsockopen("www....",80,$x,$y);

fwrite("GET request HTTP/1.1\r\nConnection: keep-alive\r\n\r\n");

while($s = fread($f,1024)){
    ...
}
Run Code Online (Sandbox Code Playgroud)

上面的摊位因为Connection: keep-alive,并与之合作Connection: close.

你怎么做而不拖延?

dre*_*010 18

它取决于响应,如果transfer-encoding响应是chunked,则在您遇到"最后一个块"(\r\n0\r\n)之前读取.

如果content-encodinggzip,则查看content-length响应头并读取那么多数据,然后对其进行充气.如果transfer-encoding也设置为chunked,则必须解除解码后的响应.

最简单的方法是构建一个简单的状态机来读取套接字的响应,同时仍有数据留给响应.

在读取分块数据时,您应该读取第一个块长度(以及任何分块扩展),然后读取与块大小一样多的数据,并执行此操作直到最后一个块.

换一种方式:

  • 读取HTTP响应头(读取小块数据,直到遇到\r\n\r\n)
  • 将响应头解析为数组
  • 如果transfer-encoding是分块,则逐个读取和去除数据.
  • 如果content-length设置了标头,则可以从套接字读取大量数据
  • 如果content-encoding是gzip,则解压缩读取的数据

执行上述步骤后,您应该已阅读完整的响应,现在可以在同一个套接字上发送另一个HTTP请求并重复此过程.

另一方面,除非您绝对需要保持连接,否则只需Connection: close在请求中设置即可安全阅读while (!feof($f)).

我目前没有任何用于读取和解析HTTP响应的PHP代码(我只是使用cURL),但如果您想查看实际代码,请告诉我,我可以解决一些问题.我还可以向您推荐一些我做过的C#代码,它完成了以上所有操作.

编辑:这是工作代码,用于fsockopen发出HTTP请求并演示读取保持活动连接与分块编码和gzip压缩的可能性.经过测试,但没有折磨 - 使用风险自负!

<?php

/**
 * PHP HTTP request demo
 * Makes HTTP requests using PHP and fsockopen
 * Supports chunked transfer encoding, gzip compression, and keep-alive
 *
 * @author drew010 <http://stackoverflow.com/questions/11125463/if-connection-is-keep-alive-how-to-read-until-end-of-stream-php/11812536#11812536>
 * @date 2012-08-05
 * Public domain
 *
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

$host = 'www.kernel.org';

$sock = fsockopen($host, 80, $errno, $errstr, 30);

if (!$sock) {
    die("Connection failed.  $errno: $errstr\n");
}

request($sock, $host, 'GET', '/');

$headers = readResponseHeaders($sock, $resp, $msg);
$body    = readResponseBody($sock, $headers);

echo "Response status: $resp - $msg\n\n";

echo '<pre>' . var_export($headers, true) . '</pre>';
echo "\n\n";
echo $body;

// if the connection is keep-alive, you can make another request here
// as demonstrated below

request($sock, $host, 'GET', '/kernel.css');
$headers = readResponseHeaders($sock, $resp, $msg);
$body    = readResponseBody($sock, $headers);

echo "Response status: $resp - $msg\n\n";

echo '<pre>' . var_export($headers, true) . '</pre>';
echo "\n\n";
echo $body;


exit;

function request($sock, $host, $method = 'GET', $uri = '/', $params = null)
{
    $method = strtoupper($method);
    if ($method != 'GET' && $method != 'POST') $method = 'GET';

    $request = "$method $uri HTTP/1.1\r\n"
              ."Host: $host\r\n"
              ."Connection: keep-alive\r\n"
              ."Accept-encoding: gzip, deflate\r\n"
              ."\r\n";

    fwrite($sock, $request);
}

function readResponseHeaders($sock, &$response_code, &$response_status)
{
    $headers = '';
    $read    = 0;

    while (true) {
        $headers .= fread($sock, 1);
        $read    += 1;

        if ($read >= 4 && $headers[$read - 1] == "\n" && substr($headers, -4) == "\r\n\r\n") {
            break;
        }
    }

    $headers = parseHeaders($headers, $resp, $msg);

    $response_code   = $resp;
    $response_status = $msg;

    return $headers;
}

function readResponseBody($sock, array $headers)
{
    $responseIsChunked = (isset($headers['transfer-encoding']) && stripos($headers['transfer-encoding'], 'chunked') !== false);
    $contentLength     = (isset($headers['content-length'])) ? $headers['content-length'] : -1;
    $isGzip            = (isset($headers['content-encoding']) && $headers['content-encoding'] == 'gzip') ? true : false;
    $close             = (isset($headers['connection']) && stripos($headers['connection'], 'close') !== false) ? true : false;

    $body = '';

    if ($contentLength >= 0) {
        $read = 0;
        do {
            $buf = fread($sock, $contentLength - $read);
            $read += strlen($buf);
            $body .= $buf;
        } while ($read < $contentLength);

    } else if ($responseIsChunked) {
        $body = readChunked($sock);
    } else if ($close) {
        while (!feof($sock)) {
            $body .= fgets($sock, 1024);
        }
    }

    if ($isGzip) {
        $body = gzinflate(substr($body, 10));
    }

    return $body;
}

function readChunked($sock)
{   
    $body = '';

    while (true) {
        $data = '';

        do {
            $data .= fread($sock, 1);
        } while (strpos($data, "\r\n") === false);

        if (strpos($data, ' ') !== false) {
            list($chunksize, $chunkext) = explode(' ', $data, 2);
        } else {
            $chunksize = $data;
            $chunkext  = '';
        }

        $chunksize = (int)base_convert($chunksize, 16, 10);

        if ($chunksize === 0) {
            fread($sock, 2); // read trailing "\r\n"
            return $body;
        } else {
            $data    = '';
            $datalen = 0;
            while ($datalen < $chunksize + 2) {
                $data .= fread($sock, $chunksize - $datalen + 2);
                $datalen = strlen($data);
            }

            $body .= substr($data, 0, -2); // -2 to remove the "\r\n" before the next chunk
        }
    } // while (true)
}

function parseHeaders($headers, &$response_code = null, &$response_message = null)
{
    $lines  = explode("\r\n", $headers);
    $return = array();

    $response = array_shift($lines);

    if (func_num_args() > 1) {
        list($proto, $code, $message) = explode(' ', $response, 3);

        $response_code    = $code;

        if (func_num_args() > 2) {
            $response_message = $message;
        }
    }

    foreach($lines as $header) {
        if (trim($header) == '') continue;
        list($name, $value) = explode(':', $header, 2);

        $return[strtolower(trim($name))] = trim($value);
    }

    return $return;
}
Run Code Online (Sandbox Code Playgroud)