本篇文章给大家分享的是有关hyperf中如何使用Swoole\Table,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
Swoole\Table的create需要在workStart之前,所以tcp服务启动之前,在server.php中配置SwooleEvent::ON_BEFORE_START监听事件
[
'name' => 'tcp',
'type' => Server::SERVER_BASE,
'host' => '0.0.0.0',
'port' => 9503,
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
SwooleEvent::ON_BEFORE_START => [\App\Tcp\ServerStartCallback::class, 'beforeStart'],
SwooleEvent::ON_WORKER_START => [\App\Tcp\TcpServer::class, 'onWorkerStart'],
SwooleEvent::ON_CONNECT => [\App\Tcp\TcpServer::class, 'onConnect'],
SwooleEvent::ON_RECEIVE => [\App\Tcp\TcpServer::class, 'onReceive'],
]
]
在ServerStartCallback中实现Swoole\Table的初始化
<?php
namespace App\Tcp;
use Hyperf\Server\ServerInterface;
use Hyperf\Server\SwooleServerFactory;
use Hyperf\Utils\ApplicationContext;
use Swoole\Server;
use Swoole\Table;
class ServerStartCallback extends \Hyperf\Framework\Bootstrap\ServerStartCallback
{
public function beforeStart()
{
$table = new Table(65536);
$table->column('fd', Table::TYPE_INT);
$table->column('reactor_id', Table::TYPE_INT);
$table->column('data', Table::TYPE_STRING, 64);
$table->create();
$container = ApplicationContext::getContainer();
$server = $container->get(Server::class);
$server->table = $table;
}
}
在TCP建立连接接收消息的时候,进行fd的绑定
<?php
declare(strict_types = 1);
namespace App\Tcp;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Contract\OnReceiveInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Server\ServerFactory;
use Hyperf\Di\Annotation\Inject;
use PBurggraf\CRC\CRC16\CRC16;
use Psr\Log\LoggerInterface;
use Swoole\Http\Request;
use Swoole\Server as SwooleServer;
use Swoole\Table;
use Swoole\WebSocket\Server;
use Hyperf\Framework\Logger\StdoutLogger;
class TcpServer implements OnReceiveInterface
{
/**
* @Inject
* @var CRC16
*/
private $crc16;
/**
* @var LoggerInterface
*/
protected $logger;
public function __construct(LoggerFactory $loggerFactory)
{
$this->logger = $loggerFactory->get('log', 'default');
}
public function onWorkerStart(SwooleServer $server, int $worker_id): void
{
}
public function onConnect(SwooleServer $server, int $fd, int $fromId): void
{
$this->logger->debug($fd);
}
public function onReceive(SwooleServer $server, int $fd, int $fromId, string $data): void
{
$this->logger->debug($fd . ' - ' . $data);
// 检测数据,如果返回的前4位字符为IMEI,则应该为设备绑定fd
if (strpos($data, 'IMEI') === 0) {
$imei = substr($data, 5);
$server->table->set((string)$fd, [
'reactor_id' => $fromId,
'fd' => $fd,
'data' => $imei
]);
}
$this->logger->debug($server->table->count());
}
}
以上就是hyperf中如何使用Swoole\Table,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/1165423/blog/4306313