A swoole-based asynchronous MQTT client library that can be used to receive or send MQTT protocol messages. QoS 0, QoS 1, and QoS 2 are supported. MQTT versions 3.1 and 3.1.1 are supported.

The installation

composer require try-to/swoole_mqttCopy the code

Example

subscribe.php

<? php use TrytoMqtt\Client; require_once __DIR__ . '/vendor/autoload.php'; $options = [ 'clean_session' => false, 'client_id' => 'demo-subscribe-123456', 'username' => '', 'password' => '', ]; $MQTT = new Client('127.0.0.1', 1883, $options); $mqtt->onConnect = function ($mqtt) { $mqtt->subscribe('/World'); }; $mqtt->onMessage = function ($topic, $content) { var_dump($topic, $content); }; $mqtt->onError = function ($exception) use ($mqtt) { echo "error\n"; // $mqtt->reconnect(1000); }; $mqtt->onClose = function () { echo "close\n"; }; $mqtt->connect();Copy the code

The command line starts with PHP subscribe.php

publish.php

<? php use TrytoMqtt\Client; require_once __DIR__ . '/.. /vendor/autoload.php'; $options = [ 'clean_session' => false, 'client_id' => 'demo-publish-123456', 'username' => '', 'password' => '', ]; $MQTT = new Client('127.0.0.1', 1883, $options); $mqtt->onConnect = function ($mqtt) { $mqtt->publish('/World', 'hello swoole mqtt'); }; $mqtt->onError = function ($exception) { echo "error\n"; }; $mqtt->onClose = function () { echo "close\n"; }; $mqtt->connect();Copy the code

Run PHP publish.php from the command line to start

Implemented interface

  • Client::__construct()
  • Client::connect()
  • Client::reconnect()
  • Client::publish()
  • Client::subscribe()
  • Client::unsubscribe()
  • Client::disconnect()
  • Client::close()
  • callback onConnect
  • callback onMessage
  • callback onError
  • callback onClose

address

Github Address Code Cloud address