douhe4336 2012-04-11 20:08
浏览 72
已采纳

HTTP响应 - >获取确切的字节数,然后关闭连接

I am running into a silly problem: I need to get a certain number of bytes, then close the connection. I've found I can extract the "Content Length" from the header, and use the length to determine just how many more bytes I should get before severing the connection. However, it appears I have made a mistake. It is only getting 40 bytes, instead of 2428 (as it should). Perhaps I am not using fgets() correctly?

Here is the code:

private static function Send($URL, $Data) {
            $server = parse_url($URL, PHP_URL_HOST);
            $port = parse_url($URL, PHP_URL_PORT);

            // If the parsing the port information fails, we will assume it's on a default port.
            // As such, we'll set the port in the switch below.
            if($port == null) {
                switch(parse_url($URL, PHP_URL_SCHEME)) {
                    case "HTTP":
                        $port = 80;
                        break;
                    case "HTTPS":
                        $port = 443;
                        break;

                }
            }

            // Check if we are using a proxy (debug configuration typically).
            if(\HTTP\HTTPRequests::ProxyEnabled) {
                $server = \HTTP\HTTPRequests::ProxyServer;
                $port = \HTTP\HTTPRequests::ProxyPort;
            }



            // Open a connection to the server.
            $connection = fsockopen($server, $port, $errno, $errstr);
            if (!$connection) {
                die("OMG Ponies!");
            }
            echo "===========================================================<BR>";
            echo "Connection Open<BR>";
            echo "The Time is " . date("H:i:su", time()) . "<BR>";
            echo "Sending Request<BR>";

            fwrite($connection, $Data);

            echo "Request Sent.";
            echo "The Time is " . date("H:i:su", time()) . "<BR>";
            $responseheader = "";
            $responsebody = "";


            /*
            \HTTP\HTTPRequests::$start = NULL;
            \HTTP\HTTPRequests::$timeout = 10;

            // @todo: Rewrite this. Should keep checking for '/r/n/r/n', then check for a content length header. If found, keep grabbing bytes, then close. If not, then close immediately.
            while(!\HTTP\HTTPRequests::safe_feof($connection, \HTTP\HTTPRequests::$start) && (microtime(true) - \HTTP\HTTPRequests::$start) < \HTTP\HTTPRequests::$timeout)
            {
                $response .= fgets($connection);
            }
            */
            echo "Getting Response<BR>";
            echo "The Time is " . date("H:i:su", time()) . "<BR>";
            while(!feof($connection) && !(strlen(strstr($responseheader,"

"))>0)) {
                $responseheader .= fgets($connection);
            }

            echo "The Header is fully received at " . date("H:i:su", time()) . "<BR>";
            echo "Header (raw):" . "<BR>";
            echo "/////////////////////////////////////////////<BR>";
            echo $responseheader . "<BR>";
            echo "/////////////////////////////////////////////<BR>";

            if((strlen(strstr($responseheader,"Content-Length:"))>0)) {
                $contentlength = ((int)(\Extract\Extract::GetContentLength($responseheader)));
                //for($i = 0; $i < $contentlength; $i++) {
                    $responsebody .= fgets($connection, $contentlength);
                //}
                echo "The Body is fully received at " . date("H:i:su", time()) . "<BR>";
                echo "Body (raw):" . "<BR>";
                echo "{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}<BR>";
                echo $responsebody . "<BR>";
                echo "{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}<BR>";
                echo "<B>!Content length is " . strlen($responsebody) . ". It should be " . $contentlength . "!</B><BR>";
            }

            echo "Response Received.<BR>";
            echo "The Time is " . date("H:i:su", time()) . "<BR>";
            fclose($connection);

            echo "Connection Closed.<BR>";
            echo "The Time is " . date("H:i:su", time()) . "<BR>";
            echo "Exiting Send() method.<BR>";
            echo "===========================================================<BR>";
            echo "<BR>";

            return $responseheader . $responsebody;
        }

And here is the output:

===========================================================
Connection Open
The Time is 15:57:29000000
Sending Request
Request Sent.The Time is 15:57:29000000
Getting Response
The Time is 15:57:29000000
The Header is fully received at 15:57:29000000
Header (raw):
/////////////////////////////////////////////
HTTP/1.1 207 Multi-Status Date: Wed, 11 Apr 2012 19:57:18 GMT Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.14 with Suhosin-Patch mod_ssl/2.2.8 OpenSSL/0.9.8g mod_wsgi/2.0 Python/2.5.2 mod_perl/2.0.3 Perl/v5.8.8 X-Powered-By: PHP/5.2.4-2ubuntu5.14 DAV: 1, 2, 3, access-control, calendar-access, calendar-schedule DAV: extended-mkcol, calendar-proxy, bind, addressbook, calendar-auto-schedule Content-Location: /davical/caldav.php/rwr26/home/ ETag: "8378ead7e628deafd91ec99dc180ad74" X-DAViCal-Version: DAViCal/0.9.9; DB/1.2.9 Content-Length: 2428 Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Content-Type: text/xml; charset="utf-8" 
/////////////////////////////////////////////
The Body is fully received at 15:57:29000000
Body (raw):
{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}

{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}
!Content length is 40. It should be 2428!
Response Received.
The Time is 15:57:29000000
Connection Closed.
The Time is 15:57:29000000
Exiting Send() method.
===========================================================

Why am I doing it this way? Apparently, I was running into some sort of a timeout error, which makes each connection stay open for 30 seconds (yes, 30 whole seconds). So I wrote this code to get the exact number of bytes, then close. Any help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dongyi6543 2012-04-21 00:02
    关注

    I changed the content line "$responsebody .= fgets($connection, $contentlength);" to "$responsebody .= stream_get_line($connection, $contentlength);". Thing is wicked fast now, and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算