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

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

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()).'

'."\n";

}

以上就介绍了基于php的json rpc原理及应用,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

jsonrpc php使用,基于php的json rpc原理及应用相关推荐

  1. jsonrpc php使用,利用php怎么编写一个json rpc框架

    利用php怎么编写一个json rpc框架 发布时间:2020-12-25 15:24:41 来源:亿速云 阅读:71 作者:Leah 本篇文章为大家展示了利用php怎么编写一个json rpc框架, ...

  2. jsonrpc php使用,php实现的一个简单json rpc框架实例

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

  3. 基于 Thingsboard 平台自定义 RPC 控制类小部件示例

    基于 Thingsboard 平台自定义 RPC 控制类小部件示例 1. 小部件介绍 2. 创建小部件 3. 部件编辑器 3.1 简介 3.2 资源 / HTML / CSS 3.3 JavaScri ...

  4. C语言编写的简单HTTP json RPC

    目录 0 概述 0.0 参考 0.1 HTTP 服务 0.2 JSON RPC HTTP错误码 0.3 目录结构 1 使用 1.1 接口访问示例 1.2 方法注册 1.3 修改监听端口 4 源码获取 ...

  5. 【RPC】---- 基于Netty实现的RPC

    基于Netty实现的RPC 一.Netty服务端和客户端 1.服务端server 1.1 NettyServer 1.2 NettyServerHandler 2.客户端client 2.1 Nett ...

  6. Crawler:基于requests库+json库+40行代码实现爬取猫眼榜单TOP100榜电影名称主要信息

    Crawler:基于requests库+json库+40行代码实现爬取猫眼榜单TOP100榜电影名称主要信息 目录 输出结果 实现代码 输出结果 实现代码 # -*- coding: utf-8 -* ...

  7. Py之Crawler:基于requests库+json库实现爬取刘若英2018导演电影《后来的我们》的插曲《再见》张震岳的几十万热评+词云:发现“再见”亦是再也不见

    Py之Crawler:基于requests库+json库实现爬取刘若英2018导演电影<后来的我们>的插曲<再见>张震岳的几十万热评+词云:发现"再见"亦是 ...

  8. 基于Jackson的JSON工具类封装 JsonUtils

    直接上代码,都有注释,一看就懂,完全满足日常开发需求 import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.f ...

  9. 用JAVA实现基于Actor模型的RPC

    基于Actor模型的RPC ReleaseNote 使用protostuff序列化(.proto文件编写恶心,与Protocol Buffer性能几乎接近) 使用Netty进行通讯(同节点RPC不走网 ...

  10. RPC原理(1)之深入RPC原理简介

    一.RPC调用原理图 下面这张图是我们微服务一次Http调用请求图: 首先在请求的过程中我们知道是有三次握手,四次挥手的流程,具体流程如下: 1.浏览器请求服务器(订单服务),请求建立连接,首先客户端 ...

最新文章

  1. 知乎热议:985 计算机视觉研究生找不到工作怎么办?
  2. 整数阶贝塞尔函数c语言,第二类整数阶贝塞尔函数(诺伊曼函数)
  3. 如何在MySQL中声明变量?
  4. linux 下opencv安装教程,linux 下 opencv安装
  5. ajax对日期处理,AJAX获取服务器当前时间及时间格式输出处理
  6. Redis夺命连环11问
  7. 新一代数据安全的制胜法宝-UBA
  8. java web redis_java web网页版redis客户端工具
  9. Java程序员晋升之路:“Java高级核心知识全面解析
  10. 智能排班系统、班次、班表、考勤、年假、调休、审批、请假、培训、值班、换班、加班、工时、自动排班、智能预测、人力需求预测、授权、团队、锁定量排、规则权重设置、菜单、角色、数据监控、工作台、axure
  11. 本地图片预览代码(支持 IE6、IE7)
  12. 带weixin扫码登陆注册|仿城通网盘源码修复版
  13. 一个简单的例子由易到难理解动态规划
  14. 小球放入盒中的方法总结(排列组合)
  15. python 解压文件 重名_Python批量重命名压缩文件
  16. R语言survival包coxph函数构建cox回归模型、ggrisk包ggrisk函数可视化Cox回归的风险评分图、使用cutoff包基于最小p值法方法计算最佳截断值(基于LIRI基因数据集)
  17. 安卓修改电池容量教程_图吧小白教程 篇三十二:手机拆换原装电池教程——替换寿命将届的原厂电池,提升手机续航...
  18. 彻底搞懂MySQL表锁、行锁和叶锁
  19. 强化学习--实验一倒立摆
  20. mysql删除列前判断_MySQL中,删除列的SQL语句是( )

热门文章

  1. 电力系统微型计算机继电保护试题,全国2010年4月自考电力系统微型计算机继电保护试题...
  2. CWMP(TR069)协议标准学习
  3. 路由交换的一些常见知识点总结
  4. nginx配置lua脚本
  5. 图形面积用计算机软件计算方法,AutoCAD2018如何算面积 计算图形面积教程
  6. 物联网基础建设-园区智能微电网设计方案
  7. 服务器与mysql数据库服务器_数据库与服务器的关系
  8. 统计·数值分析·概率论·人工智能数学基础
  9. matlab 固态 机械_忆捷固态硬盘怎么样(2款忆捷固态硬盘测评)
  10. 第一章 批判性思维概念