基於php的json rpc原理及應用

來源:互聯網
上載者:User


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教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.