PHP implementation of a simple JSON RPC framework instance, JSONRPC Framework instance _php Tutorial

Source: Internet
Author: User
Tags php server

PHP implementation of a simple JSON RPC framework instance, JSONRPC framework instance


JSON RPC is a remote invocation service in the form of a JSON message, which is a set of specifications and a series of implementations that allow programs that run on different operating systems, in different environments, to implement Internet-based procedure calls. This remote procedure call can use HTTP as the transport protocol, or it can use other transport protocols, and the content of the transfer is the JSON message body.

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

(a) PHP server Rpcserver jsonrpcserver.php

Copy CodeThe code is as follows:
Class Jsonrpcserver {
/**
* Processing a request class in which a number of requests parameters are bound
* @param object $object
* @return Boolean
*/
public static function handle ($object) {
Determine if it is an RPC JSON request
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);
Executing an interface in a request class
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 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
Copy the Code code as follows:
<?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) {
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) {
Check request Information
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;
}

Assemble as 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 ' = $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 Debugging information
if ($this->debug) {
Echo nl2br (($this->debug));
}
Inspection response Information
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;
}
}
}
?>

(c) Application examples
(1) Service End server.php
Copy the Code code as follows:
<?php
Require_once ' jsonrpcserver.php ';

Copy the Code code as follows:
Member for Test class
Require ' member.php ';
Service-side invocation
$myExample = new Member ();
Inject instance
Jsonrpcserver::handle ($myExample)
or print ' no request ';
?>

(2) Test class file, member.php
Copy the Code code as follows:
Class member{
Public Function GetName () {
Return ' Hello word '; return string
}
}

(3) Client client.php
Copy the Code code as follows:
Require_once ' jsonrpcclient.php ';

$url = ' http://localhost/rpc/server.php ';
$myExample = new Jsonrpcclient ($url);

Client Calls
try {
$name = $myExample->getname ();
Echo $name;
} catch (Exception $e) {
Echo nl2br ($e->getmessage ()). '
'." \ n ";
}

http://www.bkjia.com/PHPjc/976039.html www.bkjia.com true http://www.bkjia.com/PHPjc/976039.html techarticle PHP Implementation of a simple JSON RPC framework instance, JSONRPC Framework instance JSON RPC is a JSON for the message format of the remote Call service, it is a set of allowed to run on different operating systems, not ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.