WeChat applet - connect to MQTT

1. First install mqtt.js and mqtt.min.js to the file utils in the WeChat development applet tool, and declare them in the referenced .js file.

var mqtt= require('../../utils/mqtt.min.js')

2. You can choose a public MQTT server, which is only used for testing, which is more convenient and provided by EMQ. At the same time, you can refer to the document server link provided by EMQ
: https://www.emqx.com/zh/mqtt/public-mqtt5-broker
EMQ link: https://www.emqx.com/zh/blog/how-to- use-mqtt-in-wechat-miniprogram#%E8%AE%A2%E9%98%85%E4%B8%BB%E9%A2%98 MQTT introduction:
https://www.runoob.com/w3cnote/mqtt -intro.html
3. The code in the index is as follows:

 connectmqtt:function(){
    
    
    var that = this
    const options={
    
    
      connectTimeout:4000,
      clientId:'wsy',
      port:8084,
      username:'',//测试可以为空
      password:'',//测试可以为空
    }
    client=mqtt.connect('wxs://broker-cn.emqx.io/mqtt',options)
    client.on('connect',(e)=>{
    
    
      console.log('服务器连接成功')
      client.subscribe('这里写自己的',{
    
    qos:0},function(err){
    
    
        if(!err){
    
    
          console.log('订阅成功')
        }
      })
    })
    //信息监听
    client.on('message',function(topic,massage){
    
    
      console.log('收到'+massage.toString())
    })
    client.on('reconnect',(error)=>{
    
    
      console.log('正在重连',error)
    })
    client.on('error',(error)=>{
    
    
      console.log('连接失败',error)
    })
    
  }

4. Using MQTT.fx software to test, the test is successful as shown below
Reference document: https://cloud.tencent.com/document/product/634/14630
insert image description here
5. Video learning path:
B station up silent ocean https:// www.bilibili.com/video/BV1wq4y1U79y/?spm_id_from=333.788

Guess you like

Origin blog.csdn.net/weixin_42370166/article/details/125051798