【教程】php 对接emqx,使用swoole库,simps/mqtt

第一步、我装了宝塔的linux面板,安装了php7.4版本,


第二步、安装swoole库(直接点击 后面的设置,然后点击安装扩展,选择

第三步、编写文件server.php
/*
<?php
require ‘/www/wwwroot/47.120.78.37/vendor/autoload.php’;

use Simps\MQTT\Config\ClientConfig;
use Simps\MQTT\Client;
use Simps\MQTT\Hex\ReasonCode;
use Swoole\Coroutine;

class Types
{
const PUBLISH = 3;
const PUBACK = 4;
}

Coroutine\run(function () {
$config = new ClientConfig();
$config->setClientId(‘mqtt_client_’ . uniqid() . ‘_’ . time()); // 确保唯一
$config->setKeepAlive(10);
$config->setUsername(‘zaq5920’);
$config->setPassword(‘zaq123123’);
$config->setProtocolLevel(5);
$config->setProperties([
‘session_expiry_interval’ => 0, // 断开连接时清除会话
]);

$client = new Client(
    'mqtt.lsggkj.com',   // host
    1883,               // port
    $config
);

while (!$client->connect()) {
    echo "Failed to connect to MQTT Broker. Retrying...\n";
    Coroutine::sleep(3);
}
echo "Connected to MQTT Broker!\n";

// 订阅三个主题
$topics = [
    'zhuti1' => ['qos' => 1],
    'zhuti2' => ['qos' => 1],
    'zhuti3' => ['qos' => 1],
];
$result = $client->subscribe($topics);
echo "Subscribed to topics: " . json_encode($result) . "\n";

// 发布消息到三个主题
$publishMessages = [
    ['topic' => 'zhuti1', 'message' => 'fabu1'],
    ['topic' => 'zhuti2', 'message' => 'fabu2'],
    ['topic' => 'zhuti3', 'message' => 'fabu3'],
];

foreach ($publishMessages as $publishMessage) {
    $result = $client->publish($publishMessage['topic'], $publishMessage['message'], 1);
    if ($result) {
        echo "Message '{$publishMessage['message']}' published to topic '{$publishMessage['topic']}'\n";
    } else {
        echo "Failed to publish message '{$publishMessage['message']}' to topic '{$publishMessage['topic']}'\n";
    }
}

$timeSincePing = time();
while (true) {
    $buffer = $client->recv();
    if ($buffer && $buffer !== true) {
        echo "Received message: " . json_encode($buffer) . "\n";

        if ($buffer['type'] === Types::PUBLISH && $buffer['qos'] === 1) {
            $client->send([
                'type' => Types::PUBACK,
                'message_id' => $buffer['message_id'],
                'code' => ReasonCode::SUCCESS,
            ]);
        }
    }

    if (time() - $timeSincePing >= $config->getKeepAlive()) {
        if ($client->ping()) {
            echo "Ping sent to MQTT Broker\n";
            $timeSincePing = time();
        } else {
            echo "Ping failed. Disconnecting...\n";
            $client->close();
            break;
        }
    }

    Coroutine::sleep(0.1);
}

});

*/

第四步、启动mqtt工具订阅主题
第五步、启动server.php文件:地址填写你的文件地址。

第六步、完成

1 个赞

想问下这样设置后回报一个错误,百度看下说是用户名密码不对,但是mqttx同样的就可以链接