您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關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,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。