我花了很长时间试图让 stream_get_line 获取一个块编码的 html 文件并正确地完成,以便我可以对请求进行管道化。
这是我想到的函数。
<?php
function getURLContents($url, $ip, $port, $ssl = false, $closeConnection = false)
{
if ($ssl)
$ssl = 'ssl://';
else
$ssl = '';
$fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
if ($fp)
{
$out = 'GET '.$url." HTTP/1.1\r\n";
$out .= 'Host: '.$ip.':'.$port."\r\n";
if ($closeConnection)
$out .= "Connection: close\r\n";
else
$out .= "Connection: keep-alive\r\n";
$out .= "\r\n";
if (!fwrite($fp, $out))
{
echo 'Problem writing to socket, opening a new connection.';
fclose($fp);
$fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
fwrite($fp, $out);
}
$theData = '';
$notDone = true;
stream_set_blocking($fp, 0);
$startTime = time();
$lastTime = $startTime;
while (!feof($fp) && !$done && (($startTime + MAX_TIME_FOR_THE_RESPONSE) > time()))
{
usleep(100);
$theNewData = stream_get_line($fp, 1024, "\n");
$theData .= $theNewData;
$done = (trim($theNewData) === '0');
}
}
else
{
echo 'ERROR CONNECTING TO '.$ip.':'.$port;
return false;
}
if ($closeConnection)
fclose($fp);
return $theData;
}
?>