uniapp中mqtt的基本使用

参考文档:

[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

[4] https://blog.51cto.com/olivetree/1621128?winzoom=1

[5] https://www.emqx.com/zh/blog/mqtt-js-tutorial


1. 安装mqtt

npm install mqtt@3.0.0 --save

2. 先设置 MQTT_OPTIONS

const MQTT_OPTIONS = {
    connectTimeout: 5000,
    clientId: '47dd2bbc-937b-45d3-9ddc-c5250205d1b6',
    username: 'admin',
    password: 'H9634C07116@!#',
    clean: false
}

3. 创建一个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);

 

posted @ 2021-09-26 18:30  sunshine233  阅读(2271)  评论(0编辑  收藏  举报