jsonrpc php 扩展,php实现简易json rpc框架

RPC(Remote Procedure Call

Protocol)——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。RPC协议假定某些传输协议的存在,如TCP或UDP,为通信程序之间携带信息数据。在OSI网络通信模型中,RPC跨越了传输层和应用层。RPC使得开发包括网络分布式多程序在内的应用程序更加容易。

RPC采用客户机/服务器模式。请求程序就是一个客户机,而服务提供程序就是一个服务器。首先,客户机调用进程发送一个有进程参数的调用信息到服务进程,然后等待应答信息。在服务器端,进程保持睡眠状态直到调用信息到达为止。当一个调用信息到达,服务器获得进程参数,计算结果,发送答复信息,然后等待下一个调用信息,最后,客户端调用进程接收答复信息,获得进程结果,然后调用执行继续进行。

一、PHP服务端

server.php文件源码:

// member 为测试类(可拆开)

class member{

public function getName($name){

return 'please click '.$name ; // 返回字符串

}

}

class jsonRPCServer {

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 ('result'=> $result, 'error'=> NULL);

} else {

$response = array ('result'=> NULL, 'error' => 'unknown method or incorrect parameters');

}

} catch (Exception $e) {

$response = array ('result' => NULL, 'error' =>$e->getMessage());

}

header('content-type: text/javascript');

echo json_encode($response);

return true;

}

}

// 注入实例

$myExample = new member();

jsonRPCServer::handle($myExample) or print 'no request';

二、PHP客户端

jsonRPCClient.php 文件源码:

/*

* more:webyang.net

*/

class jsonRPCClient {

private $debug;

private $url;

/**

* @param $url

* @param bool $debug

*/

public function __construct($url,$debug = false) {

$this->url = $url;

empty($debug) ? $this->debug = false : $this->debug = 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');

}

// 拼装成一个request请求

$request = array('method' => $method, 'params' => $params);

$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));

}

if (!is_null($response['error'])) {

throw new Exception('Request error: '.$response['error']);

}

return $response['result'];

}

}

client.php 文件源码:

require_once 'jsonRPCClient.php';

//服务端地址

$url = 'http://webyang.net/server.php';

$myExample = new jsonRPCClient($url);

// 客户端调用

try {

$name = $myExample->getName("webyang.net");

echo $name ;

} catch (Exception $e) {

echo nl2br($e->getMessage()).'
'."\n";

}

访问client.php,调用服务端的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JsonRPC 2.0 Client and Server ============================= 轻量级 Json-RPC 2.0 客户端和服务端的php扩展,基于 multi_curl epoll的并发客户端,依据[jsonrpc](http://www.jsonrpc.org/)协议规范。 服务端: $server = new Jsonrpc_Server(); // style one function variable $add1 = function($a, $b){     return $a   $b; }; $server->register('addition1', $add1); // style two function string function add2($a, $b){   return $a   $b; } $server->register('addition2', 'add2'); // style three function closure $server->register('addition3', function ($a, $b) {     return $a   $b; }); //style four class method string class A  {   static public function add($a, $b)   {     return $a   $b;   } } $server->register('addition4', 'A::add'); echo $server->execute(); //output >>> //{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}} 客户端: $client = new Jsonrpc_Client(1); $client->call('http://localhost/server.php', 'addition1', array(3,5)); $client->call('http://localhost/server.php', 'addition2', array(10,20)); $client->call('http://localhost/server.php', 'addition3', array(2,8)); $client->call('http://localhost/server.php', 'addition4', array(6,15)); /* ... */ $result = $client->execute(); var_dump($result); //output >>> /* array(2) {   [0]=>   array(3) {     ["jsonrpc"]=>     string(3) "2.0"     ["id"]=>     int(110507766)     ["result"]=>     int(8)   }   [1]=>   array(3) {     ["jsonrpc"]=>     string(3) "2.0"     ["id"]=>     int(1559316299)     ["result"]=>     int(30)   }   ... } */

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值