当前位置:编程学习 > php >>

PHP 并发获取(stream_select)信息程序代码

  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. ?>
补充:Web开发 , php ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,