提交一些CAppServer.class.php的代码,供大家参考:class CAppServer
{
private $socket;
private $host;
private $port;
public function __construct($host="127.0.0.1",$port=5680) 
{
$this->host = $host;
$this->port = $port;
}
public function __destruct()
{
$this->close();
}
public function connect()
{
if(!$this->socket)
{
if( $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) )
{
if(!socket_connect($this->socket,$this->host,$this->port))
{
$this->close();
}
socket_set_option($this->socket,SOL_SOCKET,SO_LINGER,array('l_onoff'=>1,'l_linger'=>0));
}
}
}
public function close()
{
if($this->socket)
{
socket_close($this->socket);
$this->socket = null;
}
}
public function invoke($fun,$args=null,$debug=false)
{
if(!is_array($args)) $args = array();
if(!$args['user_id']) $args['user_id'] = $_SESSION['user_id'];
if(!$args['eid']) $args['eid'] = $_SESSION['eid'];
if(!$args['sid']) $args['sid'] = $_REQUEST['sid'];
if(defined('APP_INVOKE_LOCAL'))
{
$_SERVER['app_args'] = $args;
if(!$debug) 
ob_start();
$file = APP_SERVER_ROOT.'/'.$fun;
require($file);
if(!$debug) 
ob_clean();
$result = $_SERVER['app_result'];
if($debug) 
{
echo "<pre>";
print_r($result);
echo "</pre>";
}
}
else
{
//================================
// 采用Apache来做Application Server

$args = serialize($args);
$this->connect();
$buffer = "POST /{$fun} HTTP/1.0\r\n".
"Content-type: application/octet-stream\r\n".
"Content-length: ".strlen($args)."\r\n\r\n";
socket_send($this->socket,$buffer,strlen($buffer),0);
socket_send($this->socket,$args,strlen($args),0);
$data = socket_read($this->socket,1024);
if($pos = strpos($data,"\r\n\r\n"))
{
$data = substr($data,$pos+4);
}
while(true)
{
$one = socket_read($this->socket,10240);
if(strlen($one)==0)
{
break;
}
$data .= $one;
}
if($debug) echo $data;
$this->close();
$result = unserialize($data);
}
if($result['SESSION'])
{
$_SESSION = $result['SESSION'];
}
return $result;
}
}
?>

解决方案 »

  1.   

    这样也可以。
    前面的代码中有一个'APP_INVOKE_LOCAL'的定义,
    如果定义了这个宏,实际就是在本地进行require。APP_SERVER中的代码示例如下:
    <?php
    require_once('common.php');
    $_ARGS = get_app_args();... set_app_result($result);
    ?>get_app_args()和set_app_result()两个函数也是对APP_INVOKE_LOCAL宏的不同情况进行了不同的处理。
      

  2.   

    再发一段调用AppServer的代码示例: $args = array();
    $args['function'] = 'info';
    $args['ip'] = $_SERVER[REMOTE_ADDR];
    $args['id'] = ''.$_SESSION['user_id'];
    $app = new CAppServer;
    $result = $app->invoke("guest.php",$args);
      

  3.   

    多了一次http请求。
    通常情况下是用不到的。
    其实不用这种方法也可以把结构弄得很干净