【MQTT】Webman中实现MQTT的发布与订阅

2/2/2023 MQTTWenmanPHP

# 相关资料

# 安装

workerman/mqtt

composer require workerman/mqtt
1

# 实例

# publish.php

<?php

namespace app\controller;

use PhpMqtt\Client\MqttClient;
use support\Request;
use Workerman\Mqtt\Client;

class IndexController
{
    public function publish(Request $request)
    {
        $mqtt = new Client('mqtt://emqx:1883');
        $mqtt->onConnect = function($mqtt) {
            $mqtt->publish('testtopic', 'hello workerman mqtt');
        };
        $mqtt->connect();
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

通过控制器,手动触发发送信息

# subscribe.php

<?php

namespace process;

use Workerman\Connection\TcpConnection;
use Workerman\Mqtt\Client;

class Subscribe
{
    public function onConnect(TcpConnection $connection)
    {
        echo "onConnect\n";
    }

    public function onWorkerStart()
    {
        $mqtt = new Client('mqtt://emqx:1883');
        $mqtt->onConnect = function ($mqtt) {
            $mqtt->subscribe('testtopic');
        };
        $mqtt->onMessage = function ($topic, $content) {
            var_dump($topic, $content);
        };
        $mqtt->connect();

        echo "onConnect\n";
    }

    public function onWebSocketConnect(TcpConnection $connection, $http_buffer)
    {
        echo "onWebSocketConnect\n";
    }

    public function onMessage(TcpConnection $connection, $data)
    {
        $connection->send($data);
    }

    public function onClose(TcpConnection $connection)
    {
        echo "onClose\n";
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

通过自定义非监听进程 (opens new window),需要在 config/process.php 中添加如下配置启动服务即可

return [
    // ... 其它进程配置省略

    'task' => [
        'handler'  => process\TaskTest::class
    ],
];
1
2
3
4
5
6
7