php实现的一个简单json rpc框架实例


Posted in PHP onMarch 30, 2015

json rpc 是一种以json为消息格式的远程调用服务,它是一套允许运行在不同操作系统、不同环境的程序实现基于Internet过程调用的规范和一系列的实现。这种远程过程调用可以使用http作为传输协议,也可以使用其它传输协议,传输的内容是json消息体。

下面我们code一套基于php的rpc框架,此框架中包含rpc的服务端server,和应用端client;

(一)PHP服务端RPCserver jsonRPCServer.php

class jsonRPCServer {

    /**

     *处理一个request类,这个类中绑定了一些请求参数

     * @param object $object

     * @return boolean

     */

    public static function handle($object) {

       // 判断是否是一个rpc json请求

        if ($_SERVER['REQUEST_METHOD'] != 'POST' || empty($_SERVER['CONTENT_TYPE'])

            ||$_SERVER['CONTENT_TYPE'] != 'application/json') {

            return false;

        }

        // reads the input data

        $request = json_decode(file_get_contents('php://input'),true);

        // 执行请求类中的接口

        try {

            if ($result = @call_user_func_array(array($object,$request['method']),$request['params'])) {

                $response = array ( 'id'=> $request['id'],'result'=> $result,'error'=> NULL );

            } else {

                $response = array ( 'id'=> $request['id'], 'result'=> NULL,

                                        'error' => 'unknown method or incorrect parameters' );}

        } catch (Exception $e) {

            $response = array ('id' => $request['id'],'result' => NULL, 'error' =>$e->getMessage());

        }

       // json 格式输出

        if (!empty($request['id'])) { // notifications don't want response

            header('content-type: text/javascript');

            echo json_encode($response);

        }

        return true;

    }

}

(二)Rpc客户端,jsonRPCClient.php

<?php

/*

 */

class jsonRPCClient {
    private $debug;

    private $url;

    // 请求id

    private $id;

    private $notification = false;

    /**

     * @param $url

     * @param bool $debug

     */

    public function __construct($url,$debug = false) {

        // server URL

        $this->url = $url;

        // proxy

        empty($proxy) ? $this->proxy = '' : $this->proxy = $proxy;

        // debug state

        empty($debug) ? $this->debug = false : $this->debug = true;

        // message id

        $this->id = 1;

    }
    /**

     *

     * @param boolean $notification

     */

    public function setRPCNotification($notification) {

        empty($notification) ? $this->notification = false  : $this->notification = true;

    }
    /**

     * @param $method

     * @param $params

     * @return bool

     * @throws Exception

     */

    public function __call($method,$params) {

        // 检验request信息

        if (!is_scalar($method)) {

            throw new Exception('Method name has no scalar value');

        }

        if (is_array($params)) {

            $params = array_values($params);

        } else {

            throw new Exception('Params must be given as array');

        }
        if ($this->notification) {

            $currentId = NULL;

        } else {

            $currentId = $this->id;

        }
       // 拼装成一个request请求

        $request = array(  'method' => $method,  'params' => $params,'id' => $currentId);

        $request = json_encode($request);

        $this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n";

        $opts = array ('http' => array (

                                    'method'  => 'POST',

                                    'header'  => 'Content-type: application/json',

                                    'content' => $request

        ));

        //  关键几部

        $context  = stream_context_create($opts);

  if ( $result = file_get_contents($this->url, false, $context)) {

            $response = json_decode($result,true);

  } else {

   throw new Exception('Unable to connect to '.$this->url);

  }

        // 输出调试信息

        if ($this->debug) {

            echo nl2br(($this->debug));

        }

        // 检验response信息

        if (!$this->notification) {

            // check

            if ($response['id'] != $currentId) {

                throw new Exception('Incorrect response id (request id: '.$currentId.', response id: '.$response['id'].')');

            }

            if (!is_null($response['error'])) {

                throw new Exception('Request error: '.$response['error']);

            }

            return $response['result'];
        } else {

            return true;

        }

    }

}

?>

(三) 应用实例
(1)服务端 server.php

<?php

require_once 'jsonRPCServer.php';
// member 为测试类

require 'member.php';

// 服务端调用

$myExample = new member();

// 注入实例

jsonRPCServer::handle($myExample)

 or print 'no request';

?>

(2)测试类文件,member.php

class member{

    public function getName(){

        return 'hello word ' ;  // 返回字符串

    }

}

(3)客户端 client.php

require_once 'jsonRPCClient.php';
$url = 'http://localhost/rpc/server.php';

$myExample = new jsonRPCClient($url);
// 客户端调用

try {

 $name = $myExample->getName();

    echo $name ;

} catch (Exception $e) {

 echo nl2br($e->getMessage()).'<br />'."\n";

}
PHP 相关文章推荐
php的一些小问题
Jul 03 PHP
php中的三元运算符使用说明
Jul 03 PHP
php调用方法mssql_fetch_row、mssql_fetch_array、mssql_fetch_assoc和mssql_fetch_objcect读取数据的区别
Aug 08 PHP
PHP截断标题且兼容utf8和gb2312编码
Sep 22 PHP
兼容各大浏览器带关闭按钮的漂浮多组图片广告代码
Jun 05 PHP
Yii框架创建cronjob定时任务的方法分析
May 23 PHP
PHP读取word文档的方法分析【基于COM组件】
Aug 01 PHP
PHP实现的简单sha1加密功能示例
Aug 27 PHP
Laravel框架生命周期与原理分析
Jun 12 PHP
PHP PDOStatement::bindColumn讲解
Jan 30 PHP
PHP中遍历数组的三种常用方法实例分析
Jun 24 PHP
laravel请求参数校验方法
Oct 10 PHP
php实现读取内存顺序号
Mar 29 #PHP
php实现插入排序
Mar 29 #PHP
php实现插入数组但不影响原有顺序的方法
Mar 27 #PHP
WordPress自定义时间显示格式
Mar 27 #PHP
在php和MySql中计算时间差的方法详解
Mar 27 #PHP
PHP连接access数据库
Mar 27 #PHP
使用新浪微博API的OAuth认证发布微博实例
Mar 27 #PHP
You might like
php实现的mongodb操作类实例
2015/04/03 PHP
php如何控制用户对图片的访问 PHP禁止图片盗链
2016/03/25 PHP
基于yaf框架和uploadify插件,做的一个导入excel文件,查看并保存数据的功能
2017/01/24 PHP
一个刚完成的layout(拖动流畅,不受iframe影响)
2007/08/17 Javascript
Javascript模块模式分析
2008/05/16 Javascript
你必须知道的Javascript知识点之&quot;深入理解作用域链&quot;的介绍
2013/04/23 Javascript
jquery实现手风琴效果实例代码
2013/11/15 Javascript
JS的参数传递示例介绍
2014/02/08 Javascript
关于延迟加载JavaScript
2015/05/05 Javascript
浅谈javascript中new操作符的原理
2016/06/07 Javascript
让html元素随浏览器的大小自适应垂直居中的实现方法
2016/10/12 Javascript
详解js的事件代理(委托)
2016/12/22 Javascript
jQuery插件autocomplete使用详解
2017/02/04 Javascript
nodejs个人博客开发第五步 分配数据
2017/04/12 NodeJs
vue快捷键与基础指令详解
2017/06/01 Javascript
详解webpack提取第三方库的正确姿势
2017/12/22 Javascript
微信小程序五子棋游戏AI实现方法【附demo源码下载】
2019/02/20 Javascript
在vue中使用G2图表的示例代码
2019/03/19 Javascript
js中Generator函数的深入讲解
2019/04/07 Javascript
linux服务器快速卸载安装node环境(简单上手)
2021/02/22 Javascript
python模糊图片过滤的方法
2018/12/14 Python
在PyCharm中实现添加快捷模块
2020/02/12 Python
Python基于内置库pytesseract实现图片验证码识别功能
2020/02/24 Python
python 数据库查询返回list或tuple实例
2020/05/15 Python
opencv 图像加法与图像融合的实现代码
2020/07/08 Python
Pycharm中使用git进行合作开发的教程详解
2020/11/17 Python
亚马逊印度站:Amazon.in
2017/10/15 全球购物
电子商务专业实习生自我鉴定
2013/09/24 职场文书
银行求职自荐书
2014/06/25 职场文书
授权委托书
2014/09/17 职场文书
旷课检讨书范文
2014/10/30 职场文书
2014年企业团支部工作总结
2014/12/10 职场文书
推广普通话的宣传语
2015/07/13 职场文书
文明和谐家庭事迹材料(2016精选版)
2016/02/29 职场文书
2016年学校禁毒宣传活动工作总结
2016/04/05 职场文书
五年级作文之成长
2019/09/16 职场文书