请问用mqtt订阅某个主题得到的如何转发出去

不羁如风

请问用mqtt订阅某个主题得到的如何转发出去

现在我已经接收到某个订阅发布的数据,现在想把这个数据发送到前端页面,如何实现,试了好多方法,都没有实现

<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker();
$worker->onWorkerStart = function(){
    //$mqtt = new Workerman\Mqtt\Client('mqtt://1.117.155.19:1883',["username"=>"", "password"=>""]);
    $mqtt = new Workerman\Mqtt\Client('mqtt://1.117.155.19:1883');   
    $mqtt->onConnect = function($mqtt) {
        $mqtt->subscribe('demo/2');
    };
    $mqtt->onMessage = function($topic, $content){
        //如何转发$content数据呢
        var_dump($topic, $content);
    };
    $mqtt->connect();
};
Worker::runAll();
1022 1 3
1个回答

喵了个咪
<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:6666'); //<====监听websocket
$worker->onWorkerStart = function($worker) {
    $mqtt = new Workerman\Mqtt\Client('mqtt://...');   
    $mqtt->onConnect = function($mqtt) {
        $mqtt->subscribe('demo/2');
    };
    $mqtt->onMessage = function($topic, $content) use ($worker){
        //如何转发$content数据呢
        var_dump($topic, $content);
        foreach ($worker->connections as $connection) { // <======通过websocket发送数据给浏览器
            $connection->send(json_encode(['topic'=>$topic, 'content'=>$content]));
        }
    };
    $mqtt->connect();
};
Worker::runAll();

前端js

ws = new WebSocket('ws://127.0.0.1:6666'); // 连接服务端websocket 666端口
ws.onmessage = function(e){ // 当websocket发来数据时
    console.log(e.data);
}

就这么简单....

年代过于久远,无法发表回答
×
🔝