JosnRpcClient

<?php

/**
* Simple JSON-RPC interface.
*/
namespace org;

class JosnRpcClient
{
protected $host;
protected $port;
protected $version;
protected $debug;
protected $id = 0;

/**
* 初始化数据
* @param $host 主机IP
* @param $port 端口
* @param $debug debug模式(true or false)
* @param $version jsonrpc 版本号
* @param bool $debug
*/
public function __construct($host, $port, $debug = false, $version = "2.0")
{
$this->host = $host;
$this->port = $port;
this- $> = $ Version Version;
$ this-> = $ Debug Debug;
}

/ **
* request core method
* @param $ method callback method name
* @param $ params array parameter
* @return array returns the result array
* /
function request public (Method $, $ the params = Array ())
{
// inspection request information
IF {(is_scalar (Method $)!)
the throw new new \ Think \ Exception ( 'Method, Scalar NO name has value');
}
IF ( is_array ($ the params)) {
$ array_values the params = ($ the params);
} {the else
the throw new new \ Think \ Exception ( 'the Params Array MUST BE GIVEN AS');
}

// request data package
$request = json_encode(array(
'jsonrpc' => $this->version,
'method' => $method,
'params' => $params,
'id' => $this->id++
));

// 是否是debug模式
$this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n";

// curl请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->host);
curl_setopt($ch, CURLOPT_PORT, $this->port);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

$ret = curl_exec($ch);

// 输出调试信息
if ($this->debug) {
echo nl2br(($this->debug));
}

if ($ret !== false) {
$response = json_decode($ret);

if (isset($response->error)) {
//throw new RPCException($formatted->error->message, $formatted->error->code);
throw new \think\Exception('Request error: '.$response->error);
} else {
return $response;
}
} else {
throw new \think\Exception("Server did not respond: ".$this->host.':'.$this->port);
}
}
}

Guess you like

Origin www.cnblogs.com/wzjwffg/p/11277451.html