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

最新文章

  1. Swift3 - String 字符串、Array 数组、Dictionary 字典的使用
  2. 数学的东西(BZOJ1951)
  3. [译]How to Setup Sync Gateway on Ubuntu如何在ubuntu上安装sync-gateway
  4. vbox下创建共享存储
  5. lua面试基础知识
  6. OC 继承子类对象调用方法机制 子类对象访问父类中的实例变量
  7. HTML和JSON的数据交互-HTML模板
  8. gei shilei d
  9. 在Lufylegend中如何设置bitmap或者sprite的缩放和旋转中心
  10. C/C++中的常成员函数
  11. poj 3301 Texas Trip(几何+三分)
  12. Swift伟大的编程语言数据采集
  13. java类的继承的一些细节
  14. Jquery EasyUI +Ajax +Json +一般处理程序 实现数据的前台与后台的交互 --- 善良公社项目
  15. AE的空间分析(转载)
  16. 瑞芯微发布最新旗舰应用处理器-RK3588
  17. CSV的简单用法
  18. Firefox下载附件乱码的解决办法
  19. [转]VirtualBox安装CentOS7
  20. Navicat Premium for Mac 破解版地址

热门文章

  1. appium + python 自动化调试手机时 UiAutomator exited unexpectedly with code 0, signal null
  2. C++开发系列-纯虚函数和抽象类
  3. Ifconfig- Linux必学的60个命令
  4. Leetcode970. Powerful Integers强整数
  5. 关于Loadrunner非常好的英文网站
  6. 提高Modelsim仿真速度的方法(1) -- force
  7. CF1163E Magical Permutation
  8. Mysql 1864 主从错误解决方法
  9. 修改文本框和文本域placeholder样式
  10. Audio 标签的使用和自己封装一个强大的React音乐播放器