JSON RPCis a remote invocation service in JSON format, which is a set of specifications and a series of implementations that allow programs running on different operating systems, in different environments, to implement Internet-based procedure calls. ThisRemote Procedure Callcan usehttpas aTransport protocol, other transport protocols can be used, and the content of the transmission is the JSON message body.
Below we code a set of PHP-based RPC framework, which contains RPC server servers, and application-side client;
(i)PHP server Rpcserver jsonrpcserver.php
Class Jsonrpcserver {/** * handles a request class in which a number of requests parameters are bound * @param object $object * @return Boolean */P Ublic static function handle ($object) {//determines if it is an RPC JSON request if ($_server[' request_method '! = ' POST ' | | empt Y ($_server[' content_type ') | | $_server[' Content_Type ']! = ' Application/json ') {return false; }//reads the input data $request = Json_decode (file_get_contents (' Php://input '), true); Executes the interface in the request class, try {if ($result = @call_user_func_array (Array ($object, $request [' method ']), $request [' param S ']) {$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 format output if (!empty ($request [' ID ')]) {//notifications don ' t want response header (' content- Type:text/javascript '); echo Json_encode ($response); } return true; }}
Two RPC Client, jsonrpcclient.php
<?php/* */class jsonrpcclient {private $debug; Private $url; Request ID private $id; Private $notification = false; /** * @param $url * @param bool $debug */Public function __construct ($url, $debug = False) {//Serv Er 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) {emp Ty ($notification)? $this->notification = false: $this->notification = true; }/** * @param $method * @param $params * @return BOOL * @throws Exception */Public Function __ Call ($method, $params) {//Verify the request information if (!is_scalar ($method)) {throw new Exception (' Method nam E 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; }//assembled into a request $request = Array (' method ' = = $method, ' params ' + $params, ' id ' = $currentId) ; $request = Json_encode ($request); $this->debug && $this->debug.= ' * * * * * * * * * * * *. \ n ". $request." \ n "." End of Request * * * * *. " \ n "; $opts = Array (' http ' = = = Array (' method ' = ' POST '), ' Header ' = ' Content-type:application/json ', ' Content ' and $request )); Key several $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);} Output debug Information if ($this->debug) {echo nl2br ($this->debug); }//Verify response information if (! $this->notification) {//check if ($response [' id ']! = $curr Entid) {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; }}}?>
(c) Application example (1) service End server.php
<?php<span style= "White-space:pre" ></span>require_once ' jsonrpcserver.php ';
Member for test class <span style= "White-space:pre" ></span>require ' member.php '; <span style= "White-space:pre "></span>//Server calls <span style=" White-space:pre "></span> $myExample = new Member (); <span style= "White-space:pre" ></span>//injection instance <span style= "White-space:pre" ></span>jsonrpcserver::handle ( $myExample) or print ' no request ';? >
(2) Test class file, member.php
Class member{public function GetName () { return ' hello word '; return string }}
(3) Client client.php
Require_once ' jsonrpcclient.php '; $url = ' http://localhost/rpc/server.php '; $myExample = new Jsonrpcclient ($url);// The client calls try {$name = $myExample->getname (); echo $name;} catch (Exception $e) {echo nl2br ($e->getmessage ()). ' <br/> '. " \ n ";}
The principle and application of JSON RPC based on PHP