RPC是啥? 远程过程调用, 简单来说就是 另一种api调用的形式, 不过是在tcp层次的。
例子:
php 7.2.9
composer 1.8.5
composer.json
{
"name": "hprose/examples",
"description": "examples of hprose",
"authors": [
{
"name": "frans",
"email": "dafa1680@gmail.com"
}
],
"require": {
"php": ">=7.0",
"hprose/hprose": "^2.0"
}
}
server.php
<?php
require './vendor/autoload.php';
function hello($name)
{
return "Hello " . $name . PHP_EOL;
}
use Hprose\Socket\Server;
$server = new Server("tcp://0.0.0.0:1314");
$server->setErrorTypes(E_ALL);
$server->setDebugEnabled();
$server->addFunction('hello');
$server->start();
client.php
<?php
require_once "./vendor/autoload.php";
use \Hprose\Future;
use \Hprose\Socket\Client;
$test = new Client("tcp://127.0.0.1:1314");
$test->fullDuplex = true;
Future\co(function () use ($test) {
try {
var_dump((yield $test->hello("yield world1")));
var_dump((yield $test->hello("yield world2")));
var_dump((yield $test->hello("yield world3")));
var_dump((yield $test->hello("yield world4")));
var_dump((yield $test->hello("yield world5")));
var_dump((yield $test->hello("yield world6")));
} catch (\Exception $e) {
echo $e->getMessage() . PHP_EOL;
echo $e->getTraceAsString();
}
});
最后跑起来:
php server.php // 没有输出,会常驻进程, 如果有输出那就是报错啦。
php client.php // 输出:
E:\rpc\hprose-php>php client.php
E:\rpc\hprose-php\client.php:12:
string(20) "Hello yield world1
"
E:\rpc\hprose-php\client.php:13:
string(20) "Hello yield world2
"
E:\rpc\hprose-php\client.php:14:
string(20) "Hello yield world3
"
E:\rpc\hprose-php\client.php:15:
string(20) "Hello yield world4
"
E:\rpc\hprose-php\client.php:16:
string(20) "Hello yield world5
"
E:\rpc\hprose-php\client.php:17:
string(20) "Hello yield world6
"
完毕!
网友评论