• 技术文章 >php教程 >php手册

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

    2016-06-13 10:40:23原创551

    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. ?>

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:PHP 动态调用方法实例代码 下一篇:Python 判断变量是否已定义介绍
    20期PHP线上班

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• php的数据数据类型• zend studio 9.0.4 破解、汉化和字体颜色及快捷键相关设置• php下载excel无法打开的解决方法• 几个php技巧• Oracle常见问题解答
    1/1

    PHP中文网