Socket 控制器
組件安裝
composer require easyswoole/socket
Examples
關(guān)于 Socket
控制器使用的具體示例,請(qǐng)查看 demo
包解析與控制器邏輯
數(shù)據(jù)解析與控制器映射
數(shù)據(jù)解析和控制器映射,開(kāi)發(fā)者可以通過(guò)實(shí)現(xiàn) \EasySwoole\Socket\AbstractInterface\ParserInterface
接口的來(lái)實(shí)現(xiàn),然后在 encode
方法中實(shí)現(xiàn)數(shù)據(jù)解析和控制器映射。使用方法可以參考下面的示例。
下面以實(shí)現(xiàn)一個(gè) tcp socket
控制器為例。首先定義協(xié)議解析器類 TcpParser
類,該類需要實(shí)現(xiàn) \EasySwoole\Socket\AbstractInterface\ParserInterface
接口。如下:
<?php
namespace App\Parser;
use EasySwoole\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Socket\Bean\Caller;
class TcpParser implements ParserInterface
{
public function decode($raw, $client): ?Caller
{
// 數(shù)據(jù)解析,這里采用簡(jiǎn)單的json格式作為應(yīng)用層協(xié)議
$data = substr($raw, 4);
$data = json_decode($data, true);
// 實(shí)現(xiàn)與控制器和action的映射
$caller = new Caller();
$controller = !empty($data['controller']) ? $data['controller'] : 'Index';
$action = !empty($data['action']) ? $data['action'] : 'index';
$param = !empty($data['param']) ? $data['param'] : [];
$controller = "App\\TcpController\\{$controller}";
$caller->setControllerClass($controller);
$caller->setAction($action);
$caller->setArgs($param);
return $caller;
}
// ... encode 方法
}
數(shù)據(jù)的打包與響應(yīng)
對(duì)于數(shù)據(jù)的打包,開(kāi)發(fā)者可以通過(guò)實(shí)現(xiàn) \EasySwoole\Socket\AbstractInterface\ParserInterface
接口的來(lái)實(shí)現(xiàn),然后在 decode
方法中實(shí)現(xiàn)數(shù)據(jù)的打包。使用方法可以參考下面的示例。
<?php
namespace App\Parser;
use EasySwoole\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Socket\Bean\Response;
class TcpParser implements ParserInterface
{
// ... decode 方法
public function encode(Response $response, $client): ?string
{
// 實(shí)現(xiàn)對(duì)數(shù)據(jù)的打包
return pack('N', strlen(strval($response->getMessage()))) . $response->getMessage();
}
}
關(guān)于對(duì)數(shù)據(jù)的響應(yīng),則需要開(kāi)發(fā)者在控制器的 action
進(jìn)行處理,調(diào)用 $this->response()->setMessage($message)
進(jìn)行響應(yīng)調(diào)用端。參考示例如下:
<?php
namespace App\TcpController;
use EasySwoole\Socket\AbstractInterface\Controller;
class Index extends Controller
{
public function index()
{
// 這里我們響應(yīng)一個(gè)字符串'this is index'給調(diào)用端
$this->response()->setMessage('this is index');
}
}