IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> laravel7 通过http协议控制mqtt并给mqtt协议发消息 -> 正文阅读

[网络协议]laravel7 通过http协议控制mqtt并给mqtt协议发消息

想通过前端控制mqqt协议,但是必须通过后台去控制mqtt目前是后台是php框架用的laravel7

这里用到了 Workerman 官方文档

我这里会创建两个类 一个是发消息的 一个是接收消息的

发消息的 TestMqtt.php

收消息的 Subscribe.php

1.安装 Workerman

composer require workerman/workerman

2.安装 mqtt

composer require workerman/mqtt

3.通过 artisan 创建两个自定义的命令类

运行后就会在app\Console\Commands文件夹下生成一个自定义的类TestMqtt.php和Subscribe.php

php artisan make:command TestMqtt   //发消息的类
php artisan make:command Subscribe  //收消息的类

效果图

随后在app\Console\Kernel.php文件中$commands数组里添加一行刚刚生成的自定义类文件路径

   \App\Console\Commands\TestMqtt::class,
   \App\Console\Commands\Subscribe::class

效果图

4.首先我们编辑收消息的类 Subscribe.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use Workerman\Mqtt\Client;

class Subscribe extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'start:s';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'start subscribe';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $worker = new Worker();
        $worker->onWorkerStart = function () {
            $mqtt = new Client('mqtt://127.0.0.1:1883');
            $mqtt->onConnect = function ($mqtt) {
                $mqtt->subscribe('/result/out/hdl');
            };
            $mqtt->onMessage = function ($topic, $content) {
                $this->info('收到消息' . $content);
                $this->info("sub: $topic, $content");
            };
            $mqtt->connect();
        };
        Worker::runAll();
    }
}

5.编辑发消息的类 TestMqtt.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use Workerman\Mqtt\Client;

class TestMqtt extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mqtt {start}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'mqtt start';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $worker = new Worker();
        $http_port = '8898';
        $worker->onWorkerStart = function ($worker) use ($http_port) {
            $ws_worker = new Worker('http://0.0.0.0:' . $http_port);
            $ws_worker->onMessage = function ($connection,  $request) {
                $id = $request->post('id') ?? 0;
                $topic = '/result/out/hdl';//监听的主题
                $port = '1883';//mqtt端口
                $mqtt_ip = '127.0.0.1';//mqttip
                //具体options参数可以到官网去查看 https://www.workerman.net/doc/workerman/components/workemran-mqtt.html
                $options = [
                    'username' => 'chunge',
                    'password' => '1234',
                    // 'debug' => true,
                ];
                $clicke = "mqtt://$mqtt_ip:$port";
                $mqtt = new Client($clicke, $options);
                $json_encode = json_encode(array('id' => $id));
                $mqtt->onConnect = function ($res) use ($json_encode, $topic, $mqtt, $connection) {
                    $this->info('http向mqqtt发送消息:' . $json_encode);
                    $res->publish($topic, $json_encode);
                    $mqtt->disconnect();
                    $message = tcpSuccess();
                    $connection->send($message);
                };
                $mqtt->connect();
                $mqtt->onError = function (\Exception $e) use ($mqtt, $connection) {
                    $this->error('请先启动mqtt服务:' . $e->getMessage());
                    $mqtt->disconnect();
                    $message = tcpError('请先启动mqtt服务:' . $e->getMessage());
                    $connection->send($message);
                };
                $mqtt->onClose = function () {
                    $this->error('断开连接');
                };
            };
            $worker->ws_worker = $ws_worker;
            $ws_worker->listen();
        };
        /**
         * http发送成功反馈
         */
        function tcpSuccess($message = 'ok')
        {
            $res = array(
                'status' => 0,
                'message' => $message,
                'data' => [],
                'attache' => []

            );
            return json_encode($res);
        }
        /**
         * http发送失败反馈
         */
        function tcpError($message = '账户或密码错误')
        {
            $res = array(
                'status' => 9001,
                'message' => $message,
                'data' => [],
                'attache' => []

            );
            return json_encode($res);
        }
        // 运行worker
        Worker::runAll();
    }
}

6.将两个类在项目的更目录打开cmd输入以下命令运行起来

//先启动收消息的类
php artisan start:s
//最后启动发消息的类 
php artisan mqtt start

7.那么接下来就是见证奇迹的时刻

通过postman 已post方式请求发送了id值为989
奇迹图

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-12-02 17:07:55  更:2021-12-02 17:10:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年7日历 -2024/7/6 7:25:45-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码