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
<?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";
}
上一篇: 细说“VR晕动症”现阶段必须攻克的难关
下一篇: 费了我一下午的时间