当前位置: 首页 > 工具软件 > PHPMQTT > 使用案例 >

利用phpMQTT实现数据发布

仲绍晖
2023-12-01

1. github地址:https://github.com/bluerhinos/phpMQTT

2.安装:composer require bluerhinos/phpmqtt=@dev

3.上代码

<?php

namespace Helper;

use Bluerhinos\phpMQTT;

class Helper
{

    /**
     * mqtt发布消息
     */
    public static function publish($msg)
    {
        if (is_array($msg)) {
            $msg = json_encode($msg);
        }
        $server = "127.0.0.1";         // change if necessary
        $port = 1883;                     // change if necessary
        $username = "";                   // set your username
        $password = "";                   // set your password
        $client_id = 'pub_' . uniqid(); // make sure this is unique for connecting to sever - you could use uniqid()
        $mqtt = new phpMQTT($server, $port, $client_id);
        if ($mqtt->connect(true, NULL, $username, $password)) {
            $mqtt->publish("topic", $msg, 0);
            $mqtt->close();
            return true;
        } else {
            return false;
        }
    }

}

4.使用mqtt.fx工具测试,订阅该主题。

 类似资料: