zoukankan      html  css  js  c++  java
  • 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 hinkException('Method name has no scalar value');
    }
    if (is_array($params)) {
    $params = array_values($params);
    } else {
    throw new hinkException('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 *****'." ".$request." ".'***** End Of request *****'." ";

    // 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 hinkException('Request error: '.$response->error);
    } else {
    return $response;
    }
    } else {
    throw new hinkException("Server did not respond: ".$this->host.':'.$this->port);
    }
    }
    }
  • 相关阅读:
    spring mvc 获取请求中参数方式
    23种设计模式
    Liunx-Centos下安装FFmpeg
    liunx下nginx静态服务器配置SSL证书
    JDK 1.5新特性
    搭建kubenetes集群
    centos7添加虚拟IP
    Apache+tomcat配置动静分离(一个apache一个tomcat,没有做集群)
    maven使用内嵌tomcat7
    spring集成mybatis后,打印SQL语句
  • 原文地址:https://www.cnblogs.com/wzjwffg/p/11277451.html
Copyright © 2011-2022 走看看