1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <?php class JsonRPC { private $conn;
function __construct($host, $port) { $this->conn = fsockopen($host, $port, $errno, $errstr, 3); if (!$this->conn) { return false; } }
public function Call($method, $params) { if ( !$this->conn ) { return false; } $err = fwrite($this->conn, json_encode(array( 'method' => $method, 'params' => array($params), 'id' => 0, ))."\n"); if ($err === false) return false; stream_set_timeout($this->conn, 0, 3000); $line = fgets($this->conn); if ($line === false) { return NULL; } return json_decode($line,true); } }
$client = new JsonRPC("127.0.0.1", 1234); $r = $client->Call("MyMath.Add",array('num1'=>1,'num2'=>2)); var_export($r); echo "<br/>"; $r = $client->Call("MyMath.Sub",array('num1'=>'1','num2'=>'2')); var_dump($r);
|