thinkphp链接mqtt服务器,然后在订阅下发布消息

cmd打开项目根目录,安装插件,执行下面的命令

composer require php-mqtt/client

执行完成之后会在vendor 目录下有php-mqtt 文件
thinkphp链接mqtt服务器,然后在订阅下发布消息_第1张图片

然后在你的 extend文件下 新建mqtt文件 在文件中新建 Mqtt.php 下面是代码
thinkphp链接mqtt服务器,然后在订阅下发布消息_第2张图片


/*
 * @S: ========================================================
 * @Name: 控制器: 
 * @Author: Fu
 * @Date: 2022-03-25 14:20:58
 * @FilePath: /hezonyuyin/extend/mqtt/Mqtt.php
 * @E: ========================================================
 */
namespace mqtt;

use PhpMqtt\Client\MQTTClient;
class Mqtt
{
    private $server;
    private $port;
    private $clientId;
    private $username;
    private $password;
    private $clean_session;
    public function __construct($server = '', $port = '', $clientId = '', $username = '', $password = '', $clean_session = '')
    {
        $this->server =  '127.0.0.1';//这里是你的服务器地址
        $this->port =  1883;
        $this->clientId =  'php-'.uniqid();
        $this->username =  'emqx_user';
        $this->password =  NULL;
        $this->clean_session  =  FALSE;
    }

    /**
     * @S: -------------------------------
     * @Name: 方法: 连接MQTT
     * @Author: Fcy
     * @param {*}
     * @return {*}
     * @Date: 2022-03-31 09:26:12
     * @E: -------------------------------
     */    
    public function mqtt()
    {
        $mqtt = new MqttClient($this->server, $this->port, $this->clientId);
        $mqtt->connect($this->username, $this->password);
        $mqtt->loop(true);
    }

    /**
     * @S: ------------------------------
     * @Name: 方法: 发布订阅
     * @Author: Fcy
     * @param {*}
     * @return {*}
     * @Date: 2022-03-25 14:22:42
     * @E: -------------------------------
     */    
    public function publish($topic,$content)
    {
        $mqtt = new MqttClient($this->server, $this->port, $this->clientId);
        $mqtt->connect($this->username, $this->password);
        $mqtt->publish($topic,$content,0,true);
    }
    
}

在项目的控制器的方法里,实现发布消息,方法如下


namespace app\facemqtt\controller;

use think\Controller;
//引入extend文件夹里的类
use mqtt\Mqtt;
class Index extends Controller
{
    public function indexpage(){
        $this->push('topic');
        return 123;
    }
    private function push($topic, $data = [])
    {
        $mqtt = new Mqtt();
        $content = json_encode([
            'type' => 123,
            'time' => time(),
            'msg'  => '你好!',
        ]);
        //发布订阅消息,$topic 是主题,$content是发布的消息
        //然后订阅的这个主题的程序,就会收到$content消息
        $mqtt->publish($topic, $content);
    }
}

你可能感兴趣的:(服务器,android,运维)