分析easyswoole3.0源码,consoleTcpService(六)

时间:2023-03-09 16:37:51
分析easyswoole3.0源码,consoleTcpService(六)

前文讲过可以通过配置开启一个tcp服务,叫做consoleTcpservice。EasySwoole\EasySwoole\Core::83行

(new TcpService(Config::getInstance()->getConf('CONSOLE')));  

这个就是一个console的Tcp子服务。然后可以自定义客户端去和主服务通信。

注意了源码注册了一个TcpParser,EasySwoole\EasySwoole\Console\TcpParser 这个解析器要求了数据的分包规则。

在 EasySwoole\EasySwoole\Console\TcpController 下实现一个help方法,这个是当数据错误非json请求的时候返回的。 TcpParser::decode方法会对解析到的数据进行jsondecode,如果不是array就会默认匹配help的Action。

public function decode($raw, $client): ?Caller
{
// TODO: Implement decode() method.
Logger::getInstance()->console($raw);
$caller = new Caller();
$data = self::unpack($raw);
$arr = json_decode($data,true);
if(!is_array($arr)){
$arr = [
'action'=>'help',
'controller'=>TcpController::class,
'args'=>[
]
];
}else{
$arr['controller'] = TcpController::class;
}
$caller->setAction($arr['action']);
$caller->setControllerClass($arr['controller']);
$caller->setArgs($arr['args']);
return $caller;
}

付上一个客户端脚本,仅仅是测试所用

<?php
function mpack(string $data):string
{
return pack('N', strlen($data)).$data;
} function munpack(string $data):string
{
return substr($data,'4');
}
$client = new swoole_client(SWOOLE_SOCK_TCP); //连接到服务器
if (!$client->connect('127.0.0.1', 9502, 0.5))
{
die("connect failed.");
}
$data = ['action'=>'hostIp', 'args'=>[
]];
$poststr = mpack(var_export($data,true));
//$poststr = mpack(json_encode($data));
//向服务器发送数据
if (!$client->send($poststr))
{
die("send failed.");
}
//从服务器接收数据
$data = $client->recv();
if (!$data)
{
die("recv failed.");
}
print_r(munpack($data));
//关闭连接
$client->close();

分析easyswoole3.0源码,consoleTcpService(六)

当错误解析的时候会被解析到help方法。如果正确的话,那就按照上面的脚本去掉

//$poststr = mpack(json_encode($data));

再次运行,就会获取到ip地址了EasySwoole\EasySwoole\Console\TcpController::hostIp

分析easyswoole3.0源码,consoleTcpService(六)

其实最主要的命令还是那么几个控制开关和reload的命令