thinkphp使用 MQTT协议

windows服务器 启动

E:\programfile\mosquitto>mosquitto -v

1683554155: Client test-publisher disconnected.
1683554155: Received PINGREQ from test-subscriber
1683554155: Sending PINGRESP to test-subscriber
1683554166: Received PINGREQ from test-subscriber
1683554166: Sending PINGRESP to test-subscriber
1683554166: mosquitto version 2.0.15 terminating

客户端发布

安装 composer require php-mqtt/client

use app\index\model\Temperature;
use PhpMqtt\Client\MQTTClient;



  public function mq_demo()
    {
        $server   = 'localhost';//连接地址
        $port     = 1883;//连接端口
        $clientId = 'test-publisher';//客户端ID,可随意填写,也可使用rand函数生成随机的

        $mqtt = new MqttClient($server, $port, $clientId);
        $mqtt->connect();
        $mqtt->publish('temperature', '26', 0);
        $mqtt->close();
    }

服务端订阅

 public function mqtt_sub()
    {
        $server   = 'localhost';//连接地址
        $port     = 1883;//连接端口
        $clientId = 'test-subscriber';//客户端ID,可随意填写,也可使用rand函数生成随机的

        $mqtt = new MqttClient($server, $port, $clientId);
        $mqtt->connect();
        // $mqtt->subscribe('php-mqtt/client/test', function ($topic, $message) {
        //     echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
        // }, 0);

        $mqtt->subscribe('temperature', function (string $topic, string $message) {
            // 存储温度数据到数据库
            $temperature = new Temperature;
            $temperature->value = $message;
            $temperature->save();
        });
        $mqtt->loop(true);
        $mqtt->close();
    }

在这里插入图片描述

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐