Created
April 26, 2014 16:11
-
-
Save c93614/11323988 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function httpGet($host, $base) { | |
global $index; | |
//使用fsockopen会导致阻塞 | |
//$fd = fsockopen($host, 80, $errno, $errstr, 3); | |
$fd = stream_socket_client("{$host}:80", $errno, $errstr, 3, STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT); | |
$index[$fd] = 0; | |
$event = event_new(); | |
//设置一个事件 | |
//回调函数有两个默认参数,第三个为传递值 | |
event_set($event, $fd, EV_WRITE | EV_PERSIST, function($fd, $events, $arg) use($host) { | |
global $times, $limit, $index; | |
if (!$index[$fd]) { | |
$index[$fd] = 1; | |
$out = "GET / HTTP/1.1\r\n"; | |
$out .= "Host: $host\r\n"; | |
$out .= "Connection: Close\r\n\r\n"; | |
fwrite($fd, $out); | |
} else { | |
//这里没有显示全部内容,这里获取的内容按照自己的需要去处理 | |
echo substr(fread($fd, 4096), 0, 20); | |
if(feof($fd)) { | |
fclose($fd); | |
$times++; | |
echo "done\n"; | |
//如果执行到最后一个事件了那么执行完毕退出 | |
if($times == $limit) { | |
event_base_loopexit($arg[1]); | |
} | |
} | |
} | |
}, array($event, $base)); | |
event_base_set($event, $base); | |
//添加事件 | |
event_add($event); | |
} | |
$times = 0; | |
$limit = 2; | |
$index = array(); | |
$base = event_base_new(); | |
$urls = array('http://www.baidu.com', 'http://www.fbbin.com'); | |
for($i = 0; $i < $limit; $i++) { | |
echo "$i\n"; | |
httpGet($urls[$i], $base); | |
} | |
event_base_loop($base); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment