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


 

1. 新建uniapp项目

2. 安装mqtt

npm install mqtt --save

3. 创建一个mqtt客户端

// 改变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);

 

上一篇:Kafka入门第四课:Kafka节点数、分区数、分区副本数设置及Kafka压力测试


下一篇:kafka的常规操作命令