uniapp中mqtt的基本使用
约 339 字大约 1 分钟
2025-07-04
安装 mqtt
npm install mqtt@3.0.0 --save
设置 MQTT_OPTIONS
const MQTT_OPTIONS = {
connectTimeout: 5000,
clientId: '47dd2bbc-937b-45d3-9ddc-c5250205d1b6',
username: 'admin',
password: 'xxxxxxx',
clean: false
}
创建 mqtt 客户端并使用
// 连接字符串, 通过协议指定使用的连接方式
// ws 未加密 WebSocket 连接
// wss 加密 WebSocket 连接
// mqtt 未加密 TCP 连接
// mqtts 加密 TCP 连接
// wxs 微信小程序连接
// alis 支付宝小程序连接
// 改变client
// #ifdef H5
var preStr = "wss://";
var mqtt = require('mqtt'); //改变mqtt,h5可以直接写'mqtt'
// #endif
// #ifdef MP-WEIXIN||APP-PLUS
var preStr = "wxs://";
var mqtt = require('mqtt/dist/mqtt.js'); //小程序必须写'mqtt/dist/mqtt.js'
// #endif
var client = mqtt.connect(preStr + url,MQTT_OPTIONS);//mqtt.connect([url], options)
/**
* connect、error、reconnect、message、end、close都是回调函数
* 在相应的状态自然会调用
*/
client.on('connect', function() {
console.log('MQTT client is connected');
}).on('error', (e) => {
console.log('MQTT error:', e);
}).on('reconnect', function() {
console.log('MQTT client is reconnect...');
}).on('message', function(topic, message) {
console.log('topic:', topic);
console.log("message: ", message.toString());
}).on('end',function(){
console.log('MQTT client is end');
}).on('close', function() {
console.log('MQTT connection closed, now exiting.');
});
/**
* topic, msg 是根据文档定义的
* 先订阅,再发布
*/
client.subscribe(topic);
client.publish(topic, msg);
/* 退订主题 */
client.unsubscribe(topic);
参考文档:
[1] https://www.hivemq.com/blog/mqtt-client-library-mqtt-js/
[2] https://www.tabnine.com/code/javascript/functions/mqtt/MqttClient/on
[3] https://docs.cloudplugs.com/kb/Developer-Guides/MQTT-API/Javascript-Examples