PHP JSON-RPC server client implementation

xamta-Infotech, product development an expert

JSON-RPC (Remote Procedure Call) is a protocol for encoding remote procedure calls into JSON. It's a lightweight protocol for communication between a server and a client. In PHP, you can create a JSON-RPC server and client using various libraries. I'll demonstrate using the php-json-rpc library.

Server Side (Using php-json-rpc)

Install the library:

You can install it using Composer:


composer require simplito/jsonrpc

Create a server script (server.php):


<?php

require_once 'vendor/autoload.php';

// Create a new JSON-RPC server
$server = new \JsonRpc\Server(new \JsonRpc\BasicServer());

// Register a method
$server->getProcedureHandler()
       ->withCallback('add', function ($params) {
           // Check if the required parameters are present
           if (!isset($params['a']) || !isset($params['b'])) {
               throw new \JsonRpc\BaseException(-32602, "Invalid parameters");
           }

           // Perform the addition
           $result = $params['a'] + $params['b'];

           return $result;
       });

// Handle the JSON-RPC request
$server->reply();


Client Side (Using php-json-rpc)


<?php

require_once 'vendor/autoload.php';

// Create a new JSON-RPC client
$client = new \JsonRpc\Client('http://localhost/server.php');

// Call the 'add' method on the server
try {
    $result = $client->execute('add', ['a' => 5, 'b' => 3]);
    echo "Result: $result\n";
} catch (\JsonRpc\BaseException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}


Explanation:


  1. The server script (server.php) creates a JSON-RPC server using the php-json-rpc library. It registers a method named add that adds two numbers. The server then handles the incoming JSON-RPC request using $server->reply().
  2. The client script (client.php) creates a JSON-RPC client, specifies the server URL, and calls the add method on the server with parameters a and b. The result is then echoed. If an error occurs, it catches and displays the error message.
  3. Make sure to run the server script first (php server.php) and then the client script (php client.php). Adjust URLs and paths as needed for your setup.


Remember, this is a simple example, and in a real-world scenario, you may have more complex procedures, error handling, and security considerations. Additionally, consider using HTTPS for a production environment to encrypt the communication between the server and the client.


Would you like to get training or start project with us ! contact us 


Free of cost consult your project

15+ Years experienced team happy to serve you.










Revolutionizing Healthcare: Tongue Detection, Recognition, and Printing Software Solutions
Xamta Infotech | +91-85-111-533-98 | +1-70-353-750-57 | email  hi@xamta.in