当前位置:首页 > 新闻动态 > 网站文章

解决微信小程序MQTT通讯真机调试失败的问题附加可用代码

来源: 浏览:105 时间:2023-08-09

原因:模拟器上测试可以,选中了不校验合法域名,真机调试没能连接服务器,解决思路换了个mqtt.js
可参考

废话不多说!上代码
前端部分自己改改就可以用了,我懒得改了
微信小程序index.wxml

  










状态:{{state}}
位置:

index.js

// index.js
import mqtt from '../../utils/mqtt.js'    //引入mqtt
// import mqtt from '../../utils/mqtt.js';
let client = null;
// 获取应用实例
const app = getApp()
Page({
    data: {
        state:'未连接..' 
  },
public:function(ee){
//消息发送
    console.log(ee.currentTarget.dataset.id);
// 发布消息
client.publish('pop', ee.currentTarget.dataset.id);
wx.showToast({
    title: '请求成功',
    icon:'none'
})
},
connectMqtt: function() {
var clinet_id = parseInt(Math.random() * 100 + 888888888, 10);
        console.log('wx_' + clinet_id);
        const options = {
                connectTimeout: 4000, // 超时时间
                clientId: 'wx_' + clinet_id,
                username: '账号',
                password: '密码',
        }
client = mqtt.connect('wx://你的ip:8083/mqtt', options)
        console.log(client);
        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('pop', {
                        qos: 0
                }, function(err) {
                        if (!err) {
                                console.log("订阅成功")
                                that.setData({
                                    state:'已连接pop服务器'
                                })
}
                })
        })
client.on('message', function (topic, message) {
                console.log('received msg:' + message.toString());
                // wx.showToast({
                //     title: message.toString(),
                // })
        })
},
onLoad:function(){
    let that=this;
    that.connectMqtt();
},
})

无法在真机上使用的请换一下MQTT的js

地址 · ADDRESS

地址:建邺区新城科技园嘉陵江东街18号2层

邮箱:309474043@qq.Com

点击查看更多案例

联系 · CALL TEL

400-8793-956

售后专线:025-65016872

业务QQ:309474043    售后QQ:1850555641

©南京安优网络科技有限公司 版权所有   苏ICP备12071769号-4  网站地图