PHP 无阻塞请求

作者: jaclon 分类: PHP 发布时间: 2013-07-02 15:28 ė 6没有评论
function microtime_float() {
	list ( $usec, $sec ) = explode ( " ", microtime () );
	return (( float ) $usec + ( float ) $sec);
}

$time_start = microtime_float ();

$parallel = 10;
$sockets = array ();
$results = array ();
$failed = array ();

$id = 0;
$url = 'localhost:80';
$http_msg = "GET /test/test.php?user=ccc%s";
$http_msg .= " HTTP/1.0\r\n";
$http_msg .= "Host:localhost:80\r\n\r\n";

$timeout = 300;
for($i = 0; $i < $parallel; $i ++) {
	$s = stream_socket_client ( $url, $errno, $errstr, $timeout, 
STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT );
	if ($s) {
		$sockets [$id ++] = $s;
		fwrite ( $s, sprintf ( $http_msg, $i ) );
	} else {
		echo "Stream $id falied to open correctly.";
		$failed [] = sprintf ( $http_msg, $i );
	}
}

while ( count ( $sockets ) ) {
	$read = $sockets;
	stream_select ( $read, $w = null, $e = null, $timeout );
	if (count ( $read )) {
		$c = count ( $read );
		foreach ( $read as $r ) {
			$index = array_search ( $r, $sockets );
			$data = fread ( $r, 1024 );
			if (strlen ( $data ) == 0) {
				echo "Stream $index closes at " 
. date ( 'h:i:s' ) . "<br>";
				fclose ( $r );
				unset ( $sockets [$index] );
				$data = $c;
			}
			$results [] = $data;
		}
	}
}
$time_end = microtime_float ();
$time = $time_end - $time_start;

echo "Processed in $time seconds\n";

页面输出
Stream 0 closes at 03:24:38
Stream 1 closes at 03:24:38
Stream 2 closes at 03:24:38
Stream 4 closes at 03:24:38
Stream 5 closes at 03:24:38
Stream 7 closes at 03:24:38
Stream 6 closes at 03:24:38
Stream 8 closes at 03:24:38
Stream 9 closes at 03:24:38
Stream 3 closes at 03:24:38
Processed in 0.056652069091797 seconds

/test/test.php做了一个字文件操作,文件内容如下
ccc0 — 2013-07-02 15:24:38 0.77716700
ccc1 — 2013-07-02 15:24:38 0.77716700
ccc2 — 2013-07-02 15:24:38 0.78716800
ccc4 — 2013-07-02 15:24:38 0.79516800
ccc5 — 2013-07-02 15:24:38 0.79716800
ccc3 — 2013-07-02 15:24:38 0.80116800
ccc6 — 2013-07-02 15:24:38 0.81816900
ccc7 — 2013-07-02 15:24:38 0.81116900
ccc8 — 2013-07-02 15:24:38 0.81016900
ccc9 — 2013-07-02 15:24:38 0.82016900

本文出自 肥蕉博客@IT技术,热门话题,生活随笔,美图欣赏,转载时请注明出处及相应链接。

本文永久链接: http://www.bananawolf.com/html/2013/07/943.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*

Ɣ回顶部