程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP 並發獲取(stream_select)信息程序代碼

PHP 並發獲取(stream_select)信息程序代碼

編輯:關於PHP編程

  1. <?php
  2. $url = "www.ite5e.com";
  3. if(array_key_exists(url,$_GET)){
  4. $url = $_GET[url];
  5. }
  6. $hosts = array("www.xunlei.com", "www.qq.com", "www.163.com","www.baidu.com","www.kaixin.com","vip.xunlei.com");
  7. #$hosts = array($url);
  8. $timeout = 5;
  9. $status = array();
  10. $retdata = array();
  11. $sockets = array();
  12. $e = array();
  13. /* Initiate connections to all the hosts simultaneously */
  14. foreach ($hosts as $id => $host) {
  15. $errno = 0;
  16. $errstr = "";
  17. $s = stream_socket_client("$host:80", $errno, $errstr, $timeout,STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
  18. if ($s) {
  19.    $sockets[$id] = $s;
  20.    $status[$id] = "in progress";
  21. } else {
  22.    $status[$id] = "failed, $errno $errstr";
  23. }
  24. $retdata[$id] = ;
  25. }
  26. /* Now, wait for the results to come back in */
  27. while (count($sockets)) {
  28. $read = $write = $sockets;
  29.     /* This is the magic function - explained below */
  30. $n = stream_select($read, $write, $e, $timeout);
  31. if ($n > 0) {
  32.      /* readable sockets either have data for us, or are failed connection attempts */
  33.    foreach ($read as $r) {
  34.     $id = array_search($r, $sockets);
  35.     $data = fread($r, 8192);
  36.     if (strlen($data) == 0) {
  37.      if ($status[$id] == "in progress") {
  38.       $status[$id] = "failed to connect";
  39.      }
  40.      fclose($r);
  41.      unset($sockets[$id]);
  42.     } else {
  43.      $retdata[$id] .= $data;
  44.     }
  45.    }
  46.    /* writeable sockets can accept an HTTP request */
  47.    foreach ($write as $w) {
  48.     if(!is_resource($w))continue;
  49.     $id = array_search($w, $sockets);
  50.     fwrite($w, "GET / HTTP/1.0 Host: ".$hosts[$id]." ");
  51.     $status[$id] = "waiting for response";
  52.    }
  53. } else {
  54.      /* timed out waiting; assume that all hosts associated
  55.      * with $sockets are faulty */
  56.    foreach ($sockets as $id => $s) {
  57.     $status[$id] = "timed out " . $status[$id];
  58.    }
  59.    break;
  60. }
  61. }
  62. foreach ($hosts as $id => $host) {
  63. #echo "Host: $host ";
  64. #echo "Status: " . $status[$id] . " ";
  65. #echo "Retdata: " . $retdata[$id] . " ";
  66. $strs = explode(" ",$retdata[$id],2);
  67. echo isset($strs[1])?$strs[1]:$retdata[$id];
  68. }
  69. function debug($i){
  70. var_dump($i);
  71. var_dump(gettype($i));
  72. var_dump(is_resource($i));
  73. }
  74. ?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved