php table heper,如何在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的初始化

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的绑定

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());

}

}

之后就可以在业务中通过$server->table进行增删改查的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值