我也学别人模拟一下PHP多线程

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值