thread.php代码
运行结果:
<?php
/**
* PHP 模拟多线程
* @author Lornna
* 2013-07-08
*/
class thread {
private $hooks = array(); //请求的url
private $args = array(); //发送的数据
private $methods = array(); //请求方式POST,GET
/**
* 添加线程
* @param string $func 请求的url
* @param array $data 发送的数据
* @param string $method 请求方式
* @return boolean
*/
public function addthread($func, $data = array(), $method = 'get') {
$encoded = '';
if (!empty($data)) {
foreach ($data as $k=>$v) {
$encoded .= (!empty($encoded) ? "&" : "");
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
}
$this->hooks[] = $func;
$this->args[] = $encoded;
$this->methods[] = $method;
return true;
}
/**
* 运行线程
* @return array
*/
public function runthread() {
$result = array();
for($i = 0, $size = count($this->hooks); $i < $size; $i++) {
$fp=fsockopen($_SERVER['HTTP_HOST'], $_SERVER['SERVER_PORT'], $errno, $errstr, 10);
if($fp) {
if ($this->methods[$i] == 'get') {
$out = "GET /{$this->hooks[$i]}?{$this->args[$i]} HTTP/1.1\r\n";
$out .= "Host: {$_SERVER['HTTP_HOST']}\r\n";
$out .= "Connection: Close\r\n\r\n";
} else {
$out = "POST /{$this->hooks[$i]} HTTP/1.1\r\n";
$out .= "Host: {$_SERVER['HTTP_HOST']}\r\n";
$out .= "Content-Length: ".strlen($this->args[$i])."\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= $this->args[$i];
}
fputs($fp,$out);
while (!feof($fp)) {
$line = fgets($fp, 1024);
}
$result[] = $line;
fclose($fp);
}
}
return $result;
}
}
echo '<pre>start='.time().'<br>';
$thread = new thread();
$thread->addthread('test.php', array('info'=>1), 'post');
$thread->addthread('test.php', array('haha'=>1), 'get');
$thread->addthread('test.php', array('info'=>1), 'post');
$result = $thread->runthread();
print_r($result);
echo '<br/>';
echo 'end='.time().'<br>';
die();
test.php代码
<?php
if ($_GET) {
$result = json_encode($_GET + array('time'=>time()));
echo $result;
}
if ($_POST) {
$result = json_encode($_POST + array('time'=>time()));
echo $result;
}
die();
运行结果:
start=1373262541
Array
(
[0] => {"info":"1","time":1373262541}
[1] => {"haha":"1","time":1373262541}
[2] => {"info":"1","time":1373262541}
)
end=1373262541