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利用COM对象访问SQLServer、Access
Oct 09 PHP
PHP调用三种数据库的方法(2)
Oct 09 PHP
不用数据库的多用户文件自由上传投票系统(3)
Oct 09 PHP
PHP+ACCESS 文章管理程序代码
Jun 21 PHP
Codeigniter实现处理用户登录验证后的URL跳转
Jun 12 PHP
php+xml编程之xpath的应用实例
Jan 24 PHP
php实现用户登陆简单实例
Apr 04 PHP
PHP实现十进制、二进制、八进制和十六进制转换相关函数用法分析
Apr 25 PHP
PHP实现非阻塞模式的方法分析
Jul 26 PHP
浅谈php://filter的妙用
Mar 05 PHP
PHP+mysql防止SQL注入的方法小结
Apr 27 PHP
MacOS下PHP7.1升级到PHP7.4.15的方法
Feb 22 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之第一天
2006/10/09 PHP
php自动获取目录下的模板的代码
2010/08/08 PHP
PHP实现克鲁斯卡尔算法实例解析
2014/08/22 PHP
PHP Static延迟静态绑定用法分析
2016/03/16 PHP
php排序算法实例分析
2016/10/17 PHP
Laravel中Facade的加载过程与原理详解
2017/09/22 PHP
新浪的图片新闻效果
2007/01/13 Javascript
用js实现随机返回数组的一个元素
2007/08/13 Javascript
了解一点js的Eval函数
2012/07/26 Javascript
利用js实现在浏览器状态栏显示访问者在本页停留的时间
2013/12/29 Javascript
jQuery.extend()、jQuery.fn.extend()扩展方法示例详解
2014/05/08 Javascript
Javascript基础知识(三)BOM,DOM总结
2014/09/29 Javascript
javascript操作ul中li的方法
2015/05/14 Javascript
JQuery中DOM事件冒泡实例分析
2015/06/13 Javascript
JS获取时间的相关函数及时间戳与时间日期之间的转换
2016/02/04 Javascript
聊一聊JavaScript作用域和作用域链
2016/05/03 Javascript
AngularJS 单元测试(一)详解
2016/09/21 Javascript
微信小程序五星评分效果实现代码
2017/04/06 Javascript
微信小程序实现皮肤功能(夜间模式)
2017/06/18 Javascript
JS获取填报扩展单元格控件的值的解决办法
2017/07/14 Javascript
浅析Vue中method与computed的区别
2018/03/06 Javascript
文章或博客自动生成章节目录索引(支持三级)的实现代码
2020/05/10 Javascript
[00:57]辉夜杯战队访谈宣传片—VG
2015/12/25 DOTA
全面解读Python Web开发框架Django
2014/06/30 Python
利用Python操作消息队列RabbitMQ的方法教程
2017/07/19 Python
python读取xlsx的方法
2018/12/25 Python
Django框架models使用group by详解
2020/03/11 Python
python+pygame实现坦克大战小游戏的示例代码(可以自定义子弹速度)
2020/08/11 Python
Python3+PyCharm+Django+Django REST framework配置与简单开发教程
2021/02/16 Python
请问如下代码执行后a和b的值分别是什么
2016/05/05 面试题
房地产营销策划方案
2014/02/08 职场文书
学校总务处领导干部个人对照检查材料思想汇报
2014/10/06 职场文书
工程项目合作意向书
2015/05/08 职场文书
培训学校2015年度工作总结
2015/07/20 职场文书
初中英语教师个人工作总结2015
2015/07/21 职场文书
36个正则表达式(开发效率提高80%)
2021/11/17 Javascript