php通過SOCKET來並發擷取資訊

來源:互聯網
上載者:User
<?$hosts = array("www.xunlei.com", "www.qq.com", "www.163.com","www.baidu.com","www.kaixin.com","vip.xunlei.com");$timeout = 5;$status = array();$retdata = array();$sockets = array();$e = array();/* Initiate connections to all the hosts simultaneously */foreach ($hosts as $id => $host) {$errno = 0;$errstr = "";$s = stream_socket_client("$host:80", $errno, $errstr, $timeout,STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);if ($s) {   $sockets[$id] = $s;   $status[$id] = "in progress";} else {   $status[$id] = "failed, $errno $errstr";}$retdata[$id] = '';}/* Now, wait for the results to come back in */while (count($sockets)) {$read = $write = $sockets;    /* This is the magic function - explained below */$n = stream_select($read, $write, $e, $timeout);if ($n > 0) {     /* 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;    }   }   /* writeable sockets can accept an HTTP request */   foreach ($write as $w) {    if(!is_resource($w))continue;    $id = array_search($w, $sockets);    fwrite($w, "GET / HTTP/1.0\r\nHost: ".$hosts[$id]."\r\n\r\n");    $status[$id] = "waiting for response";   }} else {     /* timed out waiting; assume that all hosts associated     * with $sockets are faulty */   foreach ($sockets as $id => $s) {    $status[$id] = "timed out " . $status[$id];   }   break;}}foreach ($hosts as $id => $host) {#echo "Host: $host\n";#echo "Status: " . $status[$id] . "\n";#echo "Retdata: " . $retdata[$id] . "\n";$strs = explode("\r\n\r\n",$retdata[$id],2);echo isset($strs[1])?$strs[1]:$retdata[$id];} function debug($i){var_dump($i);var_dump(gettype($i));var_dump(is_resource($i));}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.