一個基於 swoole 的非同步 mqtt 客戶端庫,可用於接收或者傳送 mqtt 協議的訊息。支援 QoS 0、QoS 1、QoS 2。支援 MQTT 3.1 和 3.1.1 版本.
composer require try-to/swoole_mqtt
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();
命令列執行 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();
命令列執行 php publish.php
啟動
- Client::__construct()
- Client::connect()
- Client::reconnect()
- Client::publish()
- Client::subscribe()
- Client::unsubscribe()
- Client::disconnect()
- Client::close()
- callback onConnect
- callback onMessage
- callback onError
- callback onClose
本作品採用《CC 協議》,轉載必須註明作者和本文連結