Wednesday, January 5, 2011

Php Json-RPC source code (client side)

<?php

/**
* Author: James Hu
* Email: techman@navime.net
*/
class RpcClient {
  private $server_url;

  private $passcode;

  public function RpcClient($server_url, $passcode = '') {
    $this->__construct($server_url, $passcode);
  }

  public function __construct($server_url, $passcode = '') {
    $this->server_url = $server_url;
    $this->set_passcode($passcode);
  }

  public function set_passcode($passcode) {
    $this->passcode = $passcode;
  }

  public function call($func) {
    $url = $this->server_url . "?call=$func";
    
    $args = func_get_args();
    array_shift($args);
    $args = join(',', $args);

    $url .= "¶ms=" . $args;

    if(!empty($this->passcode)) $url .= "&passcode=" . $this->passcode;

    $response = file_get_contents($url);
    if(!$response) throw new Exception('no response from server');

    $data = @json_decode($response, true);
    if(!$data || !isset($data['ok']) || !isset($data['response'])) 
      throw new Exception("invalid response from server: $response");

    if($data['ok'] || $data['ok'] == 'true') return $data['response'];
    else throw new Exception($data['response']);
  }
};

?>

No comments:

Post a Comment