流方式實現多線程採集有關問題,請高手分析上

來源:互聯網
上載者:User
流方式實現多線程採集問題,請高手分析下
採集內容速度慢,我一直很頭大,最近在研究多線程採集,下面貼出比較代碼,有兩個問題,一是擷取的結果長度有點不一致;二是效率是不是還不夠高?大夥幫忙分析,測試!

PHP code
';}$timeEnd = microtimeFloat();echo sprintf("Spend time: %s second(s)\n", $timeEnd - $timeStart),'
';$timeStart = microtimeFloat();$timeout = 30;$status = array();$retdata = array();$sockets = array();$userAgent = $_SERVER['HTTP_USER_AGENT'];foreach($urls as $id => $url) { $tmp = parse_url($url); $host = $tmp['host']; $path = isset($tmp['path'])?$tmp['path']:'/'; empty($tmp['query']) or $path .= '?' . $tmp['query']; if (empty($tmp['port'])) { $port = $tmp['scheme'] == 'https' ? 443 : 80; } else $port = $tmp['port']; $fp = stream_socket_client("$host:$port", $errno, $errstr, 30); if (!$fp) { $status[$id] = "failed, $errno $errstr"; } else { $status[$id] = "in progress"; $retdata[$id] = ''; $sockets[$id] = $fp; fwrite($fp, "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: $userAgent\r\nConnection: Close\r\n\r\n"); }}// Now, wait for the results to come back inwhile (count($sockets)) { $read = $write = $sockets; //This is the magic function - explained below if (stream_select($read, $write = null, $e = null, $timeout)) { //readable sockets either have data for us, or are failed connection attempts foreach ($read as $r) { $id = array_search($r, $sockets); $data = fread($r, 8192); if (strlen($data) == 0) { if ($status[$id] == "in progress") { $status[$id] = "failed to connect"; } fclose($r); unset($sockets[$id]); } else { $retdata[$id] .= $data; } } }}foreach($retdata as $data){ $data = trim(substr($data, strpos($data, "\r\n\r\n") + 4)); echo strlen($data),'
';}$timeEnd = microtimeFloat();echo sprintf("Spend time: %s second(s)\n", $timeEnd - $timeStart);?>


------解決方案--------------------
你可以嘗試 curl_multi_.... 並發執行
這樣可儘可能的減少 php 指令,至於樓上兩位說的問題。絕不是php所能解決的

------解決方案--------------------
當然,file_get_contents()是阻塞型的,所以如果是執行多個抓取任務,當然會慢。
而socket_*(), fsockopen(), stream_*()都是非阻塞的。
------解決方案--------------------
慢到什麼程度?

試下加上這個:

$context = stream_context_create(array('http' => array('header'=>'Connection: close')));
file_get_contents(".....",false,$context);
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.