当前位置: 首页 > news >正文

jsonrpc php使用,基于php的json rpc原理及应用

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.phprequire_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教程有兴趣的朋友有所帮助。

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

相关文章:

  • php正则表达式变量替换,js正则表达式replace替换变量方法
  • php ab webbance,Apache的ab工具实例详解
  • 腾讯的PHP框架,腾讯音视频 TRTC
  • php定时刷新token,PHP定时任务获取微信access_token的方法实例分享
  • java机房上机模拟系统,机房上机安排管理系统,基于B/S模式下的JAVA系统
  • java引用技术,Java 8 方法引用
  • MATLAB简单绘图命令,简单的matlab绘图命令
  • matlab模糊控制移值到c,C/C++实现模糊控制,借助MATLAB辅助设计和fis.c文件 | 学步园...
  • matlab 稳定系统,matlab分析系统的稳定性
  • PHP的continue语句,PHP中continue语句的应用
  • php判断区间数字,如何快速判断数字在那个区间?
  • 有限差分matlab工具箱,FDTD(时域有限差分法)算法的Matlab源程序
  • matlab实现主机通信,设置主机模型和目标模型之间的通信
  • php电脑网站,PHP网站在线人数的程序代码 -电脑资料
  • 电脑php的基本方法是什么,做文员的基本电脑操作是什么
  • 【笔记】你不知道的JS读书笔记——Promise
  • angular组件开发
  • CSS中外联样式表代表的含义
  • unity如何实现一个固定宽度的orthagraphic相机
  • WordPress 获取当前文章下的所有附件/获取指定ID文章的附件(图片、文件、视频)...
  • 阿里云应用高可用服务公测发布
  • 分类模型——Logistics Regression
  • 自制字幕遮挡器
  • 摩拜创始人胡玮炜也彻底离开了,共享单车行业还有未来吗? ...
  • (2/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序
  • (2022版)一套教程搞定k8s安装到实战 | RBAC
  • (八十八)VFL语言初步 - 实现布局
  • (二十四)Flask之flask-session组件
  • (七)Knockout 创建自定义绑定
  • (原)记一次CentOS7 磁盘空间大小异常的解决过程
  • (原創) 博客園正式支援VHDL語法著色功能 (SOC) (VHDL)
  • .axf 转化 .bin文件 的方法
  • .net web项目 调用webService
  • .Net 转战 Android 4.4 日常笔记(4)--按钮事件和国际化
  • .netcore 如何获取系统中所有session_ASP.NET Core如何解决分布式Session一致性问题
  • .NET中的Exception处理(C#)
  • .secret勒索病毒数据恢复|金蝶、用友、管家婆、OA、速达、ERP等软件数据库恢复
  • /dev下添加设备节点的方法步骤(通过device_create)
  • [ CTF ] WriteUp-2022年春秋杯网络安全联赛-冬季赛
  • [ solr入门 ] - 利用solrJ进行检索
  • [AIGC] 如何建立和优化你的工作流?
  • [AutoSAR 存储] 汽车智能座舱的存储需求
  • [AutoSar]BSW_Com07 CAN报文接收流程的函数调用
  • [BUG]vscode插件live server无法自动打开浏览器
  • [Bzoj4722]由乃(线段树好题)(倍增处理模数小快速幂)
  • [CF407E]k-d-sequence
  • [codevs1288] 埃及分数
  • [C语言]——函数递归
  • [daily][archlinux][game] 几个linux下还不错的游戏
  • [Foreman]解决Unable to find internal system admin account
  • [FT]chatglm2微调
  • [json]定义、读写
  • [leetcode] 103. 二叉树的锯齿形层次遍历
  • [Luogu P3527BZOJ 2527][Poi2011]Meteors(整体二分+BIT)
  • [MRCTF2020]Ez_bypass1