feat: 实现TCP Server
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace app\net\parsers;
|
||||
|
||||
use app\net\Packet;
|
||||
|
||||
/**
|
||||
* 报文解析器工厂(单例模式)
|
||||
*/
|
||||
class PacketParserFactory
|
||||
{
|
||||
/**
|
||||
* @var self|null 单例实例
|
||||
*/
|
||||
private static ?self $instance = null;
|
||||
|
||||
/**
|
||||
* @var PacketParserInterface[] 解析器列表
|
||||
*/
|
||||
private array $parsers = [];
|
||||
|
||||
/**
|
||||
* 私有化构造函数(禁止外部 new)
|
||||
*/
|
||||
private function __construct()
|
||||
{
|
||||
$this->registerDefaultParsers();
|
||||
}
|
||||
|
||||
/**
|
||||
* 防止克隆(保障单例唯一性)
|
||||
*/
|
||||
private function __clone() {}
|
||||
|
||||
/**
|
||||
* 防止反序列化(保障单例唯一性)
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
throw new \RuntimeException('Cannot unserialize singleton ' . self::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单例实例(懒汉式:首次调用才初始化)
|
||||
* @return self
|
||||
*/
|
||||
public static function getInstance(): self
|
||||
{
|
||||
if (self::$instance === null) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册默认解析器(抽离出来,便于扩展)
|
||||
*/
|
||||
private function registerDefaultParsers(): void
|
||||
{
|
||||
$this->registerParser(new WiredReaderParser());
|
||||
$this->registerParser(new WirelessReaderParser());
|
||||
$this->registerParser(new CurrentCollectorParser());
|
||||
$this->registerParser(new NewCurrentCollectorParser());
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册解析器(支持动态扩展)
|
||||
* @param PacketParserInterface $parser
|
||||
* @return void
|
||||
*/
|
||||
public function registerParser(PacketParserInterface $parser): void
|
||||
{
|
||||
$this->parsers[] = $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建并解析Packet对象
|
||||
* @param string $rawBytes 原始报文字节数据
|
||||
* @return Packet
|
||||
*/
|
||||
public function create(string $rawBytes): Packet
|
||||
{
|
||||
$hexString = strtoupper(bin2hex($rawBytes));
|
||||
$parsedData = null;
|
||||
|
||||
// 遍历解析器找匹配的
|
||||
foreach ($this->parsers as $parser) {
|
||||
if ($parser->supports($hexString)) {
|
||||
$parsedData = $parser->parse($hexString);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new Packet($rawBytes, $parsedData);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建并解析Packet对象
|
||||
* @param string $rawBytes 原始报文字节数据
|
||||
* @return Packet
|
||||
*/
|
||||
public static function new(string $rawBytes): Packet
|
||||
{
|
||||
return self::getInstance()->create($rawBytes);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user