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

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

javascript 复制代码
composer require php-mqtt/client

执行完成之后会在vendor 目录下有php-mqtt 文件

然后在你的 extend文件下 新建mqtt文件 在文件中新建 Mqtt.php 下面是代码

php 复制代码
<?php
/*
 * @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);
    }
    
}

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

php 复制代码
<?php
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);
    }
}
相关推荐
编码浪子33 分钟前
趣味学RUST基础篇(异步)
服务器·rust·负载均衡
码农101号2 小时前
运维安全05 - iptables规则保存与恢复
运维·网络·安全
Empty_7772 小时前
SELinux安全上下文
linux·服务器·安全
sun0077003 小时前
android ndk编译valgrind
android
bug攻城狮3 小时前
解决Ubuntu中apt-get -y安装时弹出交互提示的问题
linux·运维·ubuntu
夜阑珊夭夭4 小时前
linux自定义网卡名字
linux·运维
佛天华4 小时前
centos 时间校准
linux·运维·centos
AI视觉网奇4 小时前
android studio 断点无效
android·ide·android studio
jiaxi的天空4 小时前
android studio gradle 访问不了
android·ide·android studio