小程序MQTT、mqtt超简单的连接、附带Demo

先上图看效果

图上可以清楚的看到连接参数,以及通讯参数。废话不多说上代码app.js

import mqtt from './utils/mqtt.js';
let client = null;
App({
  onLaunch: function () {
    this.connectMqtt();
  },
  connectMqtt: function() {
      
      var clinet_id = parseInt(Math.random() * 100 + 888888888, 10);
      console.log('wx_' + clinet_id);
      const options = {
          connectTimeout: 4000, // 超时时间
          clientId: 'wx_' + clinet_id,
          port: 8083,  
          username: 'xxxx',
          password: 'xxxxx',
      }
  
      client = mqtt.connect('wx://xxxxxx', options)
      client.on('reconnect', (error) => {
          console.log('正在重连:', error)
      })
  
      client.on('error', (error) => {
          console.log('连接失败:', error)
      })
  
      let that = this;
      client.on('connect', (e) => {
          console.log('成功连接服务器')
         //订阅一个主题
          client.subscribe('message.queue', {
              qos: 0
          }, function(err) {
              if (!err) {
                  console.log("订阅成功")
              }
          })
      })
      client.on('message', function (topic, message) {
          console.log('received msg:' + message.toString());
      })
  },
})

做这步之前要下载mqtt.js

https://unpkg.com/mqtt@2.18.8/dist/mqtt.js

https://unpkg.com/mqtt@2.18.8/dist/mqtt.min.js

还不会怎么办,有大招,关注下方公众号提问即可,一般最迟一天回复

posted @ 2020-12-16 14:27  正义的棒棒糖  阅读(1629)  评论(1编辑  收藏  举报