当前位置:Gxlcms > PHP教程 > PHP并发获取(stream_select)信息程序代码_PHP教程

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

时间:2021-07-01 10:21:17 帮助过:4人阅读

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/486113.htmlTechArticle?php $url = "www.ite5e.com"; if(array_key_exists(url,$_GET)){ $url = $_GET[url]; } $hosts = array("www.xunlei.com", "www.qq.com", "www.163.com","www.baidu.com","www.kaixin.com","vi...

人气教程排行