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 相关文章推荐
ftp类(myftp.php)
Oct 09 PHP
PHP4实际应用经验篇(3)
Oct 09 PHP
用PHP实现的生成静态HTML速度快类库
Mar 31 PHP
屏蔽机器人从你的网站搜取email地址的php代码
Nov 14 PHP
php addslashes 利用递归实现使用反斜线引用字符串
Aug 05 PHP
php stream_get_meta_data返回值
Sep 29 PHP
php 伪静态之IIS篇
Jun 02 PHP
Symfony2学习笔记之控制器用法详解
Mar 17 PHP
PHP中危险的file_put_contents函数详解
Nov 04 PHP
PDO::commit讲解
Jan 27 PHP
PHP简单验证码功能机制实例详解
Mar 27 PHP
laravel添加角色和模糊搜索功能的实现代码
Jun 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下对字符串的递增运算代码
2010/08/21 PHP
php+mysql大量用户登录解决方案分析
2014/12/29 PHP
jquery显示隐藏input对象
2014/07/21 Javascript
简介JavaScript中toUpperCase()方法的使用
2015/06/06 Javascript
javascript实现类似java中getClass()得到对象类名的方法
2015/07/27 Javascript
基于javascript实现九宫格大转盘效果
2020/05/28 Javascript
jQuery使用经验小技巧(推荐)
2016/05/31 Javascript
jQuery实现鼠标经过购物车出现下拉框代码(推荐)
2016/07/21 Javascript
浅谈jquery设置和获得checkbox选中的问题
2016/08/19 Javascript
原生JS轮播图插件
2017/02/09 Javascript
利用types增强vscode中js代码提示功能详解
2017/07/07 Javascript
深入理解JavaScript的值传递和引用传递
2018/10/24 Javascript
vue中进行微博分享的实例讲解
2019/10/14 Javascript
Python中关键字is与==的区别简述
2014/07/31 Python
python的schedule定时任务模块二次封装方法
2019/02/19 Python
Python3之不使用第三方变量,实现交换两个变量的值
2019/06/26 Python
Python openpyxl模块原理及用法解析
2020/01/19 Python
PIL.Image.open和cv2.imread的比较与相互转换的方法
2020/06/03 Python
Python绘制组合图的示例
2020/09/18 Python
jupyter notebook更换皮肤主题的实现
2021/01/07 Python
HTML5在a标签内放置块级元素示例代码
2013/08/23 HTML / CSS
CAT鞋英国官网:坚固耐用的靴子和鞋
2016/10/21 全球购物
如何定义一个可复用的服务
2014/09/30 面试题
会计专业自我鉴定范文
2013/10/06 职场文书
大学生职业生涯规划范文
2013/12/31 职场文书
艺术节主持词
2014/04/02 职场文书
党性锻炼的心得体会
2014/09/03 职场文书
无犯罪记录证明
2014/09/19 职场文书
党的群众路线教育实践活动领导班子整改措施
2014/10/28 职场文书
2014年科技工作总结
2014/11/26 职场文书
2014财务年终工作总结
2014/12/08 职场文书
安全先进个人材料
2014/12/29 职场文书
交通事故被告答辩状
2015/05/22 职场文书
PHP控制循环操作的时间
2021/04/01 PHP
一篇文章带你复习java知识点
2021/06/28 Java/Android
pt-archiver 主键自增
2022/04/26 MySQL