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;
}

/**
* 请求核心方法
* @param $method 回调方法名
* @param $params 参数数组
* @return array 返回结果数组
*/
public function request($method, $params=array())
{
// 检验request信息
if (!is_scalar($method)) {
throw new \think\Exception('Method name has no scalar value');
}
if (is_array($params)) {
$params = array_values($params);
} else {
throw new \think\Exception('Params must be given as array');
}

// 封装请求数据
$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);
}
}
}

转载于:https://www.cnblogs.com/wzjwffg/p/11277451.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值