Socket 控制器
組件安裝
composer require easyswoole/socket
Examples
關于 Socket
控制器使用的具體示例,請查看 demo
包解析與控制器邏輯
數據解析與控制器映射
數據解析和控制器映射,開發者可以通過實現 \EasySwoole\Socket\AbstractInterface\ParserInterface
接口的來實現,然后在 encode
方法中實現數據解析和控制器映射。使用方法可以參考下面的示例。
下面以實現一個 tcp socket
控制器為例。首先定義協議解析器類 TcpParser
類,該類需要實現 \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
{
// 數據解析,這里采用簡單的json格式作為應用層協議
$data = substr($raw, 4);
$data = json_decode($data, true);
// 實現與控制器和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 方法
}
數據的打包與響應
對于數據的打包,開發者可以通過實現 \EasySwoole\Socket\AbstractInterface\ParserInterface
接口的來實現,然后在 decode
方法中實現數據的打包。使用方法可以參考下面的示例。
<?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
{
// 實現對數據的打包
return pack('N', strlen(strval($response->getMessage()))) . $response->getMessage();
}
}
關于對數據的響應,則需要開發者在控制器的 action
進行處理,調用 $this->response()->setMessage($message)
進行響應調用端。參考示例如下:
<?php
namespace App\TcpController;
use EasySwoole\Socket\AbstractInterface\Controller;
class Index extends Controller
{
public function index()
{
// 這里我們響應一個字符串'this is index'給調用端
$this->response()->setMessage('this is index');
}
}