Skip to content

MQTT 客户端接入指南

JavaScript (MQTT.js)

mqtt.js 是最流行的 Node.js 和浏览器端 MQTT 客户端库。

安装

```bash npm install mqtt --save ```

连接与发布/订阅

```javascript const mqtt = require('mqtt')

// 连接配置 const options = { clientId: 'client-' + Math.random().toString(16).substr(2, 8), username: 'client1', password: 'secret_password', clean: true, // true: 清除会话, false: 保留会话 keepalive: 60 // 心跳间隔 (秒) }

// WS 连接 (浏览器) 或 TCP 连接 (Node.js) const client = mqtt.connect('wss://mqtt.example.com:9001', options) // const client = mqtt.connect('mqtt://mqtt.example.com:1883', options)

client.on('connect', function () { console.log('Connected to Broker')

// 订阅主题 (QoS 1) client.subscribe('sensors/temperature', { qos: 1 }, function (err) { if (!err) { console.log('Subscribed success')

  // 发布消息
  client.publish('sensors/temperature', '25.5', { qos: 1, retain: false })
}

}) })

client.on('message', function (topic, message) { // message is Buffer console.log(Received [${topic}]: ${message.toString()}) })

client.on('error', function(err) { console.error('Connection error: ', err) client.end() }) ```

Python (Paho MQTT)

Eclipse Paho 是 Python 的标准 MQTT 客户端。

安装

```bash pip install paho-mqtt ```

示例代码

```python import paho.mqtt.client as mqtt

连接回调

def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}") # 重新订阅 (重连时自动恢复) client.subscribe("sensors/#")

消息回调

def on_message(client, userdata, msg): print(f"{msg.topic} {msg.payload.decode('utf-8')}")

client = mqtt.Client() client.username_pw_set("client1", "secret_password") client.on_connect = on_connect client.on_message = on_message

连接 Broker

如果需要 SSL,请先把 client.tls_set() 配置好

client.connect("mqtt.example.com", 1883, 60)

阻塞运行,处理网络循环

client.loop_forever() ```