Principle and application of json rpc based on php

WBOY
Release: 2016-08-08 09:27:12
Original
1056 people have browsed it

Copy after login

json rpc is a remote calling service with json as the message format. It is a set of specifications and a series of implementations that allow programs running in different operating systems and different environments to implement Internet-based process calls. This kind of remote procedure call can use http as the transmission protocol, or other transmission protocols, and the transmitted content is the json message body.

Below we code a set of RPC framework based on PHP, which contains RPC server and application client;

(1) PHP server 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;
    }
}
Copy after login

(2) Rpc client, 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;
        }
    }
}
?>
Copy after login

(3) Application example

(1) Server server.php

<?php
<span style="white-space:pre">	</span>require_once 'jsonRPCServer.php';
Copy after login
// member 为测试类
<span style="white-space:pre">	</span>require 'member.php';
<span style="white-space:pre">	</span>// 服务端调用
<span style="white-space:pre">	</span>$myExample = new member();
<span style="white-space:pre">	</span>// 注入实例
<span style="white-space:pre">	</span>jsonRPCServer::handle($myExample)
	or print 'no request';
?>
Copy after login

(2) test Class file, member.php

class member{
    public function getName(){
        return 'hello word ' ;  // 返回字符串
    }
}
Copy after login

(3) Client 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";
}
Copy after login


The above introduces the principles and applications of json rpc based on php, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template