mqtt:轻量级物联网消息推送协议。
目录
一、介绍
1、官方文档
1)npm网
2) 中文网
MQTT中文网_MQTT 物联网接入平台-MQTT.CN
2、官方示例
二、准备工作
1、安装依赖包
npm install mqtt--save
2、示例版本
"mqtt": "^4.3.7",
三、使用步骤
1、在单页面引入 ' mqtt'
import mqtt from 'mqtt';
2、配置
const mqttConfig = {
mqtt: '地址',
mqttTopics: `主题`, // 多个主题用,分割
mqttOptions: {
port: '8083', // 端口号
clientId: (Math.random() * 10).toString(), // 客户ID, 这里用的随机数
username: '用户', // 用户名
password: '密码', // 密码
// 如果clientId不为空,默认会随机重新生成一个clientId,避免连接冲突
// 如果设置customClientId = true,不随机生成,使用用户自定义的固定的clientId
customClientId: false,
},
};
3、使用
变量名.connectMqtt(mqttConfig);
注:部分方法/数据的完整版在完整示例展示
四、完整示例
function connectMqtt() {
const mqttConfig = {
mqtt: '地址',
mqttTopics: `主题`, // 多个主题用,分割
mqttOptions: {
port: '8083', // 端口号
clientId: (Math.random() * 10).toString(), // 客户ID, 这里用的随机数
username: '用户', // 用户名
password: '密码', // 密码
// 如果clientId不为空,默认会随机重新生成一个clientId,避免连接冲突
// 如果设置customClientId = true,不随机生成,使用用户自定义的固定的clientId
customClientId: false,
},
};
topology.connectMqtt(mqttConfig);
topology.mqttClient.on('message', (topic, message) => {
// console.log(`[mqtt] Received message:`, message);
// 一些操作
....
});
// 当发生错误时,打印错误信息
topology.mqttClient.on('error', (error) => {
console.error('[mqtt] Error:', error);
});
topology.mqttClient.on('connect', (message) => {
console.log('[mqtt] connect', message);
});
topology.mqttClient.on('disconnect', (message) => {
console.log('[mqtt] disconnect', message);
});
}
connectMqtt()
tips
1、在线mqtt客户端:Easy-to-Use Online MQTT Client | Try Now