<?php
//Lingp Create 2011-01-18
//处理RPC请求
 
class CPhpRpc
{
	var $host;
	var $port;
	
	function 	CPhpRpc()
	{
		global $Config;
		$this->host = $Config["rpc_host"];
		$this->port = $Config["rpc_port"];
	}
	
	//发送HTTP请求 $host:远程服务主机IP $port:远程服务端口 $request:请求内容
	function HttpRequest($host, $port, $request, &$response)
	{
		if($request == "") return false;
		
		//打开远程服务端口
    $fp = fsockopen($host, $port, $errno, $errstr, 30);
		if(!$fp)
		{
			 echo "$errstr ($errno)<br>\n";	
			 return false;
		}
		
		//生成HTTP协议
		$rpc_server = "/RPC2"; //RPC服务器端文件
		$protocol = "POST $rpc_server HTTP/1.1\nUser-Agent: XMLRPC++ 0.7\nHost: ". $host .":".$port."\nContent-Type: text/xml\nContent-Length: ".strlen($request). "\r\n\r\n" . $request;
		
		//发送HTTP协议
		if (!fputs($fp, $protocol, strlen($protocol)))
    {
     	echo "发送HTTP请求失败";
      return false;
    }
		
		//读取返回信息
		$response = fread($fp, 8192);
		
    //关闭连接资源
   	fclose($fp);
   	
   	return true;
	}
	
	//调用RPC方法 $rpc_method: RPC方法名称 $rpc_params: RPC调用参数 $callback_func:回调函数
	function CallRpc($rpc_method, $rpc_params)
	{
		$response = "";
		$xml = "";
		
		//生成请求XML
		$output_options = array(
           "output_type" => "xml",
           "verbosity" => "pretty",
           "escaping" => array("markup"), //这个设置是关键
           "version" => "xmlrpc",
           "encoding" => "utf-8");
      
		$request = iconv("UTF-8", 'gbk',  xmlrpc_encode_request($rpc_method, $rpc_params, $output_options) );
		
		//发送请求
		if( $this->HttpRequest($this->host, $this->port,$request, $response)) 
			$xml=(substr($response, strpos($response, "\r\n\r\n")+4));
		return $xml;
	}
	
};
?>