既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Go语言开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
│ Client.php // 客户端
│ composer.json // 主要为了自动加载
│ Server.php // 服务端
│
├─Service // 存放各种服务的文件夹
│ CartService.php // 具体的服务类
│
└─vendor
│ autoload.php
##### 基本原理
`rpc` 使用 `tcp` 调用的基本原理就是将需要调用的服务类,和要调用的类中的方法,在 `tcp` 参数中传过来,然后在服务端解析参数,调用指定类中的方法。
##### 演示
Client.php
<?php namespace rpc; class Client { protected $service; public function __call($name, $arguments) { if ($name == 'service') { $this->service = $arguments[0]; return $this; } $json_data = json_encode([ 'service' => $this->service, 'action' => $name, 'param' => $arguments[0], ]); $client = new \Swoole\Client(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 9501, -1)) { exit("connect failed. Error: {$client->errCode}\n"); } $client->send($json_data); $result = $client->recv(); var_dump($result); $client->close(); } } $client = new Client(); $client->service('CartService')->getList(1); ``` Server.php ``` <?php require\_once 'vendor/autoload.php'; class Server { protected $server; public function \_\_construct() { $this->server = new \Swoole\Server("127.0.0.1", 9501); $this->onConnect(); $this->onReceive(); $this->onClose(); $this->start();; } public function onConnect() { $this->server->on('Connect', function ($serv, $fd) { echo "Client: Connect.\n"; }); } public function onReceive() { $this->server->on('Receive', function ($serv, $fd, $from\_id, $data) { $data = json\_decode($data, true); $service = $data['service']; $action = $data['action']; $page = $data['param']; $class = "rpc\\Service\\" . $service; $instance = new $class; $result = json\_encode($instance->$action($page)); $serv->send($fd, $result); }); } public function onClose() { $this->server->on('Close', function ($serv, $fd) { echo "Client: Close.\n"; }); } public function start() { $this->server->start(); } } $server = new Server(); ``` CartService.php ``` ![img](https://img-blog.csdnimg.cn/img_convert/cce707c44271fe972c267c6e0ff3f370.png) ![img](https://img-blog.csdnimg.cn/img_convert/613c336a36c435844098f187312d7ef6.png) ![img](https://img-blog.csdnimg.cn/img_convert/c1d8261708b9af81aa9dd05643d2416a.png) **既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Go语言开发知识点,真正体系化!** **由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新** **[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)** 知识点,真正体系化!** **由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新** **[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)**