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+JS无限级可伸缩菜单详解(简单易懂)
Jan 02 PHP
PHP clearstatcache()函数详解
Mar 02 PHP
PHP操作mysql函数详解,mysql和php交互函数
May 19 PHP
PHP 登录完成后如何跳转上一访问页面
Jan 14 PHP
php中curl、fsocket、file_get_content三个函数的使用比较
May 09 PHP
PHP实现根据图片色界在不同位置加水印的方法
Aug 08 PHP
PHP+MySQL实现无极限分类栏目的方法
Dec 23 PHP
php实现中文转数字
Feb 18 PHP
PHP实现的简单AES加密解密算法实例
May 29 PHP
PHP有序表查找之二分查找(折半查找)算法示例
Feb 09 PHP
laravel validate 设置为中文的例子(验证提示为中文)
Sep 29 PHP
Yii 框架使用数据库(databases)的方法示例
May 19 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
Windows下的PHP安装文件线程安全和非线程安全的区别
2014/04/23 PHP
php上传图片之时间戳命名(保存路径)
2014/08/15 PHP
Yii2中设置与获取别名的函数(setAlias和getAlias)用法分析
2016/07/25 PHP
Laravel学习教程之request validation的编写
2017/10/25 PHP
PHP fopen函数用法实例讲解
2019/02/15 PHP
PHP+redis实现微博的推模型案例分析
2019/07/10 PHP
php和js实现根据子网掩码和ip计算子网功能示例
2019/11/09 PHP
js 动态选中下拉框
2009/11/26 Javascript
jQuery控制图片的hover效果(smartRollover.js)
2012/03/18 Javascript
javascript截取字符串(通过substring实现并支持中英文混合)
2013/06/24 Javascript
jQuery中prevAll()方法用法实例
2015/01/08 Javascript
jQuery实现的Tab滑动选项卡及图片切换(多种效果)小结
2015/09/14 Javascript
Jquery 效果使用详解
2015/11/23 Javascript
Vue组件和Route的生命周期实例详解
2018/02/10 Javascript
了解ESlint和其相关操作小结
2018/05/21 Javascript
JS实现的全选、全不选及反选功能【案例】
2019/02/19 Javascript
jQuery实现图片下载代码
2019/07/18 jQuery
Vue实现商品详情页的评价列表功能
2019/09/04 Javascript
Egg Vue SSR 服务端渲染数据请求与asyncData
2019/11/24 Javascript
d3.js实现图形缩放平移
2019/12/19 Javascript
Python yield 使用浅析
2015/05/28 Python
深入浅析Python字符编码
2015/11/12 Python
Python 序列的方法总结
2016/10/18 Python
利用python 下载bilibili视频
2020/11/13 Python
HTML5 与 XHTML2
2008/10/17 HTML / CSS
快时尚眼镜品牌,全国连锁眼镜店:LOHO眼镜生活
2018/10/08 全球购物
奥地利时尚、美容、玩具和家居之家:Kastner & Öhler
2020/04/26 全球购物
大学生入党思想汇报
2014/01/01 职场文书
简单英文演讲稿
2014/01/01 职场文书
教师旷工检讨书
2014/01/18 职场文书
党员批评与自我批评发言材料
2014/10/14 职场文书
教师廉洁自律个人总结
2015/02/10 职场文书
党员个人总结自评
2015/02/14 职场文书
Go语言切片前或中间插入项与内置copy()函数详解
2021/04/27 Golang
MybatisPlus代码生成器的使用方法详解
2021/06/13 Java/Android
nginx设置资源请求目录的方式详解
2022/05/30 Servers