MQTT 协议使用发布/订阅模型。客户端可以向代理发布消息,其他客户端可以订阅该消息的主题。本文分享如何使用 PHP 和 python 向 MQTT 代理发布消息,其中包含如何将消息发布到指定主题的 MQTT 代理的示例。
使用 PHP 将消息发布到 MQTT Broker
- 将库添加
php-mqtt/client
到composer.json
文件:
"require": {
"php-mqtt/client": "^1.1"
}
- 从命令行安装库:
composer install
- 向 MQTT 代理发布消息:
<?php
use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MqttClient;
require_once __DIR__.'/vendor/autoload.php';
const MQTT_HOST = '192.168.0.174';
const MQTT_PORT = 1883;
const MQTT_CLIENT_ID = 'PHP-MQTT-client';
const MQTT_USER = 'YOUR MQTT USER';
const MQTT_PASSWORD = 'YOUR MQTT USER PASSWORD';
const TOPIC = 'php/test';
$client = new MqttClient(MQTT_HOST, MQTT_PORT, MQTT_CLIENT_ID);
$settings = (new ConnectionSettings)
->setUsername(MQTT_USER)
->setPassword(MQTT_PASSWORD);
$client->connect($settings, true);
$data = 'Hello';
$client->publish(TOPIC, $data);
使用 Python 将消息发布到 MQTT Broker
paho-mqtt
从命令行安装库:
pip install paho-mqtt
- 向 MQTT 代理发布消息:
import paho.mqtt.client as paho
MQTT_HOST = '192.168.0.174'
MQTT_PORT = 1883
MQTT_CLIENT_ID = 'Python-MQTT-client'
MQTT_USER = 'YOUR MQTT USER'
MQTT_PASSWORD = 'YOUR MQTT USER PASSWORD'
TOPIC = 'python/test'
client = paho.Client(MQTT_CLIENT_ID)
client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
client.connect(MQTT_HOST, MQTT_PORT)
data = 'Hello'
client.publish(TOPIC, data)
版权声明:本文内容转自互联网,本文观点仅代表作者本人。本站仅提供信息存储空间服务,所有权归原作者所有。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至1393616908@qq.com 举报,一经查实,本站将立刻删除。