From d08f6b931cdfbba57f73a4e337daf9e85297d085 Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Thu, 8 Aug 2024 11:01:24 +0800 Subject: [PATCH] Add wildcard example --- examples/wildcard.php | 62 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 examples/wildcard.php diff --git a/examples/wildcard.php b/examples/wildcard.php new file mode 100644 index 0000000..dce4d58 --- /dev/null +++ b/examples/wildcard.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, + * please view the LICENSE file that was distributed with this source code. + */ + +include_once __DIR__ . '/bootstrap.php'; + +use Simps\MQTT\Client; +use Simps\MQTT\Protocol\Types; +use Swoole\Coroutine; + +Coroutine\run(function () { + $client = new Client(SIMPS_MQTT_REMOTE_HOST, SIMPS_MQTT_PORT, getTestConnectConfig()); + $will = [ + 'topic' => 'simps-mqtt/users/byebye', + 'qos' => 0, + 'retain' => 0, + 'message' => 'byebye', + ]; + $client->connect(true, $will); + $topics['simps-mqtt/users/#'] = 0; + $client->subscribe($topics); + $timeSincePing = time(); + while (true) { + try { + $buffer = $client->recv(); + if ($buffer && $buffer !== true) { + var_dump($buffer); + // QoS1 PUBACK + if ($buffer['type'] === Types::PUBLISH && $buffer['qos'] === 1) { + $client->send( + [ + 'type' => Types::PUBACK, + 'message_id' => $buffer['message_id'], + ], + false + ); + } + if ($buffer['type'] === Types::DISCONNECT) { + echo "Broker is disconnected\n"; + $client->close(); + break; + } + } + if ($timeSincePing <= (time() - $client->getConfig()->getKeepAlive())) { + $buffer = $client->ping(); + if ($buffer) { + echo 'send ping success' . PHP_EOL; + $timeSincePing = time(); + } + } + } catch (\Throwable $e) { + throw $e; + } + } +});