workerman\mqtt在使用 'protocol_level' => 5 時(shí)連接,然后消息的回調(diào)第一次主題的參數(shù)是正確的,接收第二次以后得消息回調(diào),主題就為空了
$mqtt->onMessage = function ($topic, $content, $packet) {
echo $topic . ":" . $content . PHP_EOL;
};
第一次可以正常顯示,第二次以后$topic 就為空了
<?php
require __DIR__ . '/vendor/autoload.php';
use Workerman\Timer;
use Workerman\Worker;
$worker = new Worker('websocket://0.0.0.0:8282');
$worker->name = 'mqtt';
// 這里進(jìn)程數(shù)必須設(shè)置為1
$worker->count = 1;
$worker->onWorkerStart = function (Worker $worker) {
//初始化mqtt進(jìn)行連接
$mqtt = new Workerman\Mqtt\Client('mqtt://127.0.0.1:1883', array(
'debug' => false,
"client_id" => "workerman_server",
"keepalive" => 60,
"username" => "workerman_server", "password" => "Ufo@8888",
"clean_session" => false,
'properties' => [
'session_expiry_interval' => 60,
'receive_maximum' => 65535,
'topic_alias_maximum' => 65535,
],
'protocol_level' => 5, //使用協(xié)議5時(shí)接收到訂閱消息回調(diào)函數(shù)中topic會(huì)有空值的問題,所以不能使用5的協(xié)議版本
));
$mqtt->onConnect = function (Workerman\Mqtt\Client $mqtt) {
//連接成功后啟動(dòng)一個(gè)心跳主題進(jìn)行定時(shí)發(fā)布
Timer::add(5, function () use ($mqtt) {
$mqtt->publish('heart',
'{"cmd":"heart", "time":"' . date('Y-m-d H:i:s') . '"}',
[
'qos' => 0,
'retain' => 0,
'dup' => 0,
]
);
});
//默認(rèn)連接成功訂閱 heart主題
$mqtt->subscribe('heart');
};
$mqtt->onMessage = function ($topic, $content, $packet) {
echo $topic . ":" . $content . PHP_EOL;
};
// 連接mqtt
$mqtt->connect();
};
Worker::runAll();
消息回調(diào),第一次可以顯示回調(diào)的主題,以后進(jìn)不能顯示了
Ubuntu22.04
workerman v4.1.16
workerman\mqtt v1.6
把你的腳本拷貝了一遍,沒改任何東西,測(cè)試正常。
mqtt服務(wù)端用的mosquitto
和php版本沒關(guān)系,可能是mqtt客戶端不是最新,或者mqtt服務(wù)端有問題。
我測(cè)試的環(huán)境版本如下
workerman/mqtt 1.6
mqtt服務(wù)端 mosquitto 2.0.18