PHP code example of mix / jsonrpc-client
1. Go to this page and download the library: Download mix/jsonrpc-client library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mix / jsonrpc-client example snippets
$client = new \Mix\JsonRpc\Client\Compatible\JsonRpcTcpClient([
'host' => '127.0.0.1',
'port' => 9503,
'timeout' => 5,
]);
$method = 'hello.world';
$params = [];
$id = 0;
$ret = $client->call($method, $params, $id);
var_dump($ret);
$chan1 = new \Mix\Core\Coroutine\Channel();
xgo(function () use ($chan1) {
$client = new \Mix\JsonRpc\Client\Coroutine\JsonRpcTcpClient([
'host' => '127.0.0.1',
'port' => 9503,
'timeout' => 5,
]);
$method = 'hello.world';
$params = [];
$id = 0;
try {
$ret = $client->call($method, $params, $id);
$chan1->push($ret);
} catch (\Throwable $e) {
$chan1->push(null);
}
});
$chan2 = new \Mix\Core\Coroutine\Channel();
xgo(function () use ($chan2) {
$client = new \Mix\JsonRpc\Client\Coroutine\JsonRpcTcpClient([
'host' => '127.0.0.1',
'port' => 9503,
'timeout' => 5,
]);
$method = 'hello.world';
$params = [];
$id = 0;
try {
$ret = $client->call($method, $params, $id);
$chan2->push($ret);
} catch (\Throwable $e) {
$chan2->push(null);
}
});
list($ret1, $ret2) = [$chan1->pop(), $chan2->pop()];
// 可对两次请求的结果做计算并发送给客户端
applications\common\src\Libraries\Dialers\JsonRpcTcpClientDialer.php
namespace Common\Libraries\Dialers;
use Mix\Pool\DialerInterface;
/**
* Class JsonRpcTcpClientDialer
* @package Common\Libraries\Dialers
* @author liu,jian <[email protected] >
*/
class JsonRpcTcpClientDialer implements DialerInterface
{
/**
* 拨号
* @return \Mix\JsonRpc\Client\Coroutine\JsonRpcTcpClient
*/
public function dial()
{
return \Mix\JsonRpc\Client\Coroutine\JsonRpcTcpClient::newInstance();
}
}
$chan1 = new \Mix\Core\Coroutine\Channel();
xgo(function () use ($chan1) {
$rpc = app()->rpcPool->getConnection();
$method = 'hello.world';
$params = [];
$id = 0;
try {
$ret = $rpc->call($method, $params, $id);
$rpc->release(); // 不手动释放的连接不会归还连接池,会在析构时丢弃
$chan1->push($ret);
} catch (\Throwable $e) {
$chan1->push(null);
}
});
$chan2 = new \Mix\Core\Coroutine\Channel();
xgo(function () use ($chan2) {
$rpc = app()->rpcPool->getConnection();
$method = 'hello.world';
$params = [];
$id = 0;
try {
$ret = $rpc->call($method, $params, $id);
$rpc->release(); // 不手动释放的连接不会归还连接池,会在析构时丢弃
$chan2->push($ret);
} catch (\Throwable $e) {
$chan2->push(null);
}
});
list($ret1, $ret2) = [$chan1->pop(), $chan2->pop()];
// 可对两次请求的结果做计算并发送给客户端