作者:誰不曾年少輕狂過
第二個:echo $cli->getUserInfo(array('name' => '張三', 'age' => 27)); 調用對應的tcpdump 抓的包 tcpdump tcp port 8000 -w mm.pcap
mm.pcap
------------------------------------------------------------------------------------------------------------------
RPC全稱為Remote Procedure Call,翻譯過來為"遠端過程調用"。主要應用于不同的系統之間的遠端通信和互相調用。
檔案結構
image.png
User.php
<?php
/**
* 服務檔案
* Class User
*/
class User {
/**
* 擷取使用者ID
* @return string
*/
public function test() {
// todo
{
}
return '10000';
}
/**
* 擷取使用者資訊
* @param $params
* @return string
*/
public function getUserInfo($params) {
// todo
{
}
return json_encode($params);
}
}
RpcServer.php
<?php
/**
* rpc 服務端
* Class RpcServer
*/
class RpcServer {
protected $serv = null;
/**
* 建立rpc服務,映射RPC服務
* RpcServer constructor.
* @param $host
* @param $port
* @param $path
*/
public function __construct($host, $port, $path) {
//建立tcp socket服務
$this->serv = stream_socket_server("tcp://{$host}:{$port}", $errno, $errstr);
if (!$this->serv) {
exit("{$errno} : {$errstr} \n");
}
//RPC服務目錄是否存在
$realPath = realpath(__DIR__ . $path);
if ($realPath === false || !file_exists($realPath)) {
exit("{$path} error \n");
}
//解析資料,執行業務邏輯
while (true && $this->serv) {
$client = stream_socket_accept($this->serv);
if ($client) {
//讀取并解析資料
$buf = fread($client, 2048);
$buf = json_decode($buf, true);
$class = $buf['class'];
$method = $buf['method'];
$params = $buf['params'];
//調用服務檔案
if ($class && $method) {
$file = $realPath . '/' . $class . '.php';
if (file_exists($file)) {
require_once $file;
$obj = new $class();
//如果有參數,則傳入指定參數
if (!$params) {
$data = $obj->$method();
} else {
$data = $obj->$method($params);
}
//傳回結果
fwrite($client, $data)