<?php // 引入composer下载的库 require_once __DIR__ . '/composer/grpc/vendor/autoload.php'; require_once __DIR__ . '/composer/protobuf/vendor/autoload.php'; // 引入grpc_php_plugin生成的4个*.php文件 require_once __DIR__ . '/GPBMetadata/Proto/Calculator.php'; require_once __DIR__ . '/proto/CalculatorClient.php'; require_once __DIR__ . '/proto/Nums.php'; require_once __DIR__ . '/proto/Result.php'; $hostname = '192.168.***.***:10086'; // gRPC服务器主机地址,无需写tcp://协议 $client = new Proto\CalculatorClient($hostname, [ 'credentials' => Grpc\ChannelCredentials::createInsecure(), ]); $nums = new Proto\Nums(); $result = new Proto\Result(); //========== 加法运算 ==========// $nums->setNum1(5); $nums->setNum2(2); [$result, $status] = $client->Add($nums)->wait(); if ($status->code !== 0) { echo '调用Calculator.Add()失败:' . $status->details . PHP_EOL; } else { $num1 = $nums->getNum1(); $num2 = $nums->getNum2(); $num = $result->getNum(); echo "调用Calculator.Add()成功:{$num1} + {$num2} = {$num}" . PHP_EOL; } //========== 减法运算 ==========// $nums->setNum1(5); $nums->setNum2(2); [$result, $status] = $client->Subtract($nums)->wait(); if ($status->code !== 0) { echo "调用Calculator.Subtract()失败:" . $status->details . PHP_EOL; } else { $num1 = $nums->getNum1(); $num2 = $nums->getNum2(); $num = $result->getNum(); echo "调用Calculator.Subtract()成功:{$num1} - {$num2} = {$num}" . PHP_EOL; } //========== 乘法运算 ==========// $nums->setNum1(5); $nums->setNum2(2); [$result, $status] = $client->Multiply($nums)->wait(); if ($status->code !== 0) { echo "调用Calculator.Multiply()失败:" . $status->details . PHP_EOL; } else { $num1 = $nums->getNum1(); $num2 = $nums->getNum2(); $num = $result->getNum(); echo "调用Calculator.Multiply()成功:{$num1} * {$num2} = {$num}" . PHP_EOL; } //========== 除法运算(除数不为零) ==========// $nums->setNum1(5); $nums->setNum2(2); [$result, $status] = $client->Divide($nums)->wait(); if ($status->code !== 0) { echo "调用Calculator.Divide()失败:" . $status->details . PHP_EOL; } else { if ($result->getError() !== '') { echo "调用Calculator.Divide()出错:" . $result->getError() . PHP_EOL; } else { $num1 = $nums->getNum1(); $num2 = $nums->getNum2(); $num = $result->getNum(); echo "调用Calculator.Divide()成功:{$num1} / {$num2} = {$num}" . PHP_EOL; } } //========== 除法运算(除数为零) ==========// $nums->setNum1(5); $nums->setNum2(0); [$result, $status] = $client->Divide($nums)->wait(); if ($status->code !== 0) { echo "调用Calculator.Divide()失败:" . $status->details . PHP_EOL; } else { if ($result->getError() !== '') { echo "调用Calculator.Divide()出错:" . $result->getError() . PHP_EOL; } else { $num1 = $nums->getNum1(); $num2 = $nums->getNum2(); $num = $result->getNum(); echo "调用Calculator.Divide()成功:{$num1} / {$num2} = {$num}" . PHP_EOL; } } //========== 输出结果·开始 ==========// // 调用Calculator.Add()成功:5 + 2 = 7 // 调用Calculator.Subtract()成功:5 - 2 = 3 // 调用Calculator.Multiply()成功:5 * 2 = 10 // 调用Calculator.Divide()成功:5 / 2 = 2.5 // 调用Calculator.Divide()出错:除数不能为零 //========== 输出结果·结束 ==========//
Copyright © 2024 码农人生. All Rights Reserved