A simple json rpc framework instance implemented by php

Source: Internet
Author: User

A simple json rpc framework instance implemented by php

This article mainly introduces a simple json rpc framework instance implemented by php. This article provides the RPC server and client code and Application Instances. For more information, see

 

 

Json rpc is a remote call service in json format, it is a set of Internet-based process calling specifications and a series of implementations that allow programs running in different operating systems and environments. For this Remote Procedure Call, you can use http as the transmission protocol or other transmission protocols. The transmitted content is the json message body.

Below we code a php-based rpc framework, which contains the rpc server and application client;

(1) PHP server RPCserver jsonRPCServer. php

 

The Code is as follows:


Class jsonRPCServer {
/**
* Process a request class, which is bound with some request parameters.
* @ Param object $ object
* @ Return boolean
*/
Public static function handle ($ object ){
// Determine whether the request 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 );
// Execute the interface in the 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 output
If (! Empty ($ request ['id']) {// notifications don't want response
Header ('content-type: text/javascript ');
Echo json_encode ($ response );
}
Return true;
}
}

 

(2) Rpc client, jsonRPCClient. php

Copy the 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 the 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;
}

// Construct a 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 ";
$ Opts = array ('http' => array (
'Method' => 'post ',
'Header' => 'content-type: application/json ',
'Content' => $ request
));
// Key Components
$ 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 ));
}
// Check the response information
If (! $ This-> notification ){
// Check
If ($ response ['id']! = $ CurrentId ){
Throw new Exception ('encrect 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;
}
}
}
?>

 

(3) Application Instances
(1) server. php

The Code is as follows:


<? Php
Require_once 'jsonserver. php ';

 

 

The Code is as follows:


// Member is a test class
Require 'member. php ';
// Server call
$ MyExample = new member ();
// Inject instance
JsonRPCServer: handle ($ myExample)
Or print 'no request ';
?>

 

(2) test files: member. php

The Code is as follows:


Class member {
Public function getName (){
Return 'Hello word'; // return a string
}
}

 

(3) client. php

The Code is as follows:


Require_once 'jsonclient. php ';

 

$ Url = 'HTTP: // localhost/rpc/server. php ';
$ MyExample = new jsonRPCClient ($ url );

// Client call
Try {
$ Name = $ myExample-> getName ();
Echo $ name;
} Catch (Exception $ e ){
Echo nl2br ($ e-> getMessage (). '<br/>'. "\ n ";
}

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.