stevenjin 2025-01-03 22:22 采纳率: 96.8%
浏览 41
已结题

uniAPP开发App使用MQTT通讯EMQX Cloud,真机调试时异常

1.uniAPP开发小程序和APP,使用MQTT通讯EMQX Cloud。
2.用网页h5调试能收到订阅消息,但发布成app,在手机上真机运行时,提示:
连接异常TypeError: s is not a constructor at pages/mqttPages/mqttPages.vue:132


<template>
    <view class="home">
        <view class="mqttPswordtype">
            <radio-group @change="radioChange">
                <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in radDataArr" :key="item.value">
                    <radio :value="item.value" :checked="index === current" />
                    {{item.name}}
                </label>
            </radio-group>
        </view>
        <view class="mqttTest">
            <button type="primary" @click="connect">mqtt 连接</button>
            <button type="primary" @click="subscribe">mqtt 订阅</button>
            <button type="primary" @click="publish">mqtt 发布</button>
            <button type="primary" @click="unsubscribe">取消订阅</button>
            <button type="primary" @click="unconnect">断开连接</button>
            <view>message:{{ receiveMessage.toString() }}</view>
        </view>
    </view>
</template>
 
<script>
    import mqtt from '@/utils/mqtt4.1.0.js';
    export default {
        data() {
            return {
                radDataArr: [{
                        value: 'uniAppH5',
                        name: '网页',
                        checked: 'true'
                    },
                    {
                        value: 'uniAppWx01',
                        name: '微信仿真'
                    },
                    {
                        value: 'uniAppWx02',
                        name: '微信手机'
                    }
                ],
                current: 0,
                receiveMessage: "",
                mqttServeInfo: {
                    IP: 'qcf13859.ala.asia-southeast1.emqxsl.com',
                    port: '8084',
                    postfix: '/mqtt',
                },
                mqttClient: null,
                //MQTT连接的配置
                mqttOptions: {
                    wsOptions: {},
                    protocolVersion: 5, //MQTT连接协议版本
                    clientId: '',
                    keepalive: 60,
                    clean: false,
                    username: 'steven',
                    password: '123456',
                    reconnectPeriod: 1000, //1000毫秒,两次重新连接之间的间隔
                    connectTimeout: 30 * 1000, //1000毫秒,两次重新连接之间的间隔
                    resubscribe: true //如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
                },
                Qos: 2,
                onTopic: 'testtopic/#',
                onSub: 'testtopic/#',
            }
        },
        methods: {
            radioChange: function(evt) {
                for (let i = 0; i < this.radDataArr.length; i++) {
                    if (this.radDataArr[i].value === evt.detail.value) {
                        this.current = i;
                        this.mqttOptions.username = evt.detail.value
                        break;
                    }
                }
            },
            connect: function() {
                try {
 
                    var hosts = '',
                        // #ifdef APP-PLUS
                        hosts = 'wss://' + this.mqttServeInfo.IP + ':' + this.mqttServeInfo.port + this.mqttServeInfo
                        .postfix
                    console.log("APP-PLUS:" + hosts);
                    // #endif
 
                    // #ifdef H5
                    hosts = 'wss://' + this.mqttServeInfo.IP + ':' + this.mqttServeInfo.port + this.mqttServeInfo
                        .postfix
                    console.log("H5:" + hosts);
                    //#endif
 
                    // #ifdef MP-WEIXIN
                    hosts = 'wxs://' + this.mqttServeInfo.IP + ':' + this.mqttServeInfo.port + this.mqttServeInfo
                        .postfix
                    console.log("MP-WEIXIN:" + hosts);
                    //#endif 
                    if (this.mqttClient == null || this.mqttClient.connented == false) {
                        uni.showLoading({
                            title: '连接中···'
                        })
                        var clientId = this.mqttOptions.username + '_' + Math.random().toString(16).substr(2, 8);
                        console.log("生成的随机clientId为:" + clientId);
                        this.mqttOptions.clientId = clientId;
                        this.mqttClient = mqtt.connect(
                            hosts,
                            this.mqttOptions
                        );
 
                        this.mqttClient.on('connect', () => {
                            uni.hideLoading();
                            this.showToast('连接成功', 1000, 'success')
                            this.subscribe()
                        });
                        this.mqttClient.on('message', (topic, message) => {
                            console.log('收到来自' + topic + '的消息' + message.toString());
                            this.receiveMessage = message
 
                        });
                    }
 
                    this.mqttClient.on('reconnect', error => {
                        uni.hideLoading();
                        this.showToast('正在重连···', 1000)
 
                    });
                    this.mqttClient.on('error', error => {
                        uni.hideLoading();
                        this.showToast('连接失败!', 1000)
                    });
                } catch (e) {
                    console.log("连接异常" + e);
                }
 
            },
            subscribe: function() {
                // 判断是否已成功连接
                if (!this.mqttClient || !this.mqttClient.connected) {
                    this.showToast('客户端未连接', 1000)
                    return;
                }
 
                this.mqttClient.subscribe(this.onTopic, {
                    qos: this.Qos
                }, error => {
                    if (!error) {
                        this.showToast('订阅成功', 1000, 'success')
                        console.log('订阅成功');
                    }
                });
 
                /* //订阅多个主题
            this.mqttClient.subscribe(['one', 'two', 'three'], { qos: 1 }, err => {
                console.log(err || '订阅成功');
                this.show(err || '订阅成功');
             });
            
                    // 订阅不同 qos 的不同主题
                    this.mqttClient.subscribe(
                        [
                            { hello: 1 },
                            { 'one/two/three': 2 },
                            { '#': 0 }
                        ],
                        (err) => {
                          this.show();console.log(err || '订阅成功')
                        },
                    )
        
        
            }); */
            },
            publish: function() {
                // 判断是否已成功连接
                if (!this.mqttClient || !this.mqttClient.connected) {
                    this.showToast('客户端未连接', 1000)
                    return;
                }
                if (this.sendMassage != '') {
                    // var send = '{"code": 200, "msg": "发送打1111指令", "data": "2.doc"}';
 
                    // 定义JSON对象
                    const messageq = {
                        code: 200,
                        msg: '发送打印指令',
                        data: '2.doc'
                    }
 
                    // 将JSON对象转换为JSON字符串
                    const message1 = JSON.stringify(messageq)
                    this.mqttClient.publish(this.onSub, message1, error => {
                        console.log(error || '消息发布成功');
                        this.showToast('消息发布成功', 1000, 'success')
                    });
                } else {
                    this.showToast('发布消息为空', 1000)
                }
 
            },
            unsubscribe: function() {
                this.mqttClient.unsubscribe(
                    // topic, topic Array, topic Array-Onject
                    // ['one', 'two', 'three'],
                    this.onTopic,
                    err => {
                        console.log(err || '取消订阅成功');
                        this.showToast('取消订阅成功', 1000, 'success')
                    }
                );
            },
            unconnect: function() {
                if (!this.mqttClient || !this.mqttClient.connected) {
                    this.showToast('客户端未连接', 1000)
                    return;
                }
                this.mqttClient.end();
                //this.mqttClient = null
                this.showToast('成功断开连接', 1000, 'success')
                console.log('断开连接');
            },
            showToast: function(title, time, icon = 'none') {
                uni.showToast({
                    title: title,
                    icon: icon,
                });
                setTimeout(function() {
                    uni.hideToast();
                }, time);
            },
        }
    }
</script>
 
<style lang="scss">
    .mqttPswordtype {
        height: 100rpx;
        background: #F7F8FA;
        white-space: pre-wrap;
 
    }
 
    .mqttTest {
        button {
            margin: 20rpx 10rpx;
            height: 100rpx;
            color: #F7F8FA;
        }
    }
</style>

  • 写回答

1条回答 默认 最新

  • 关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    从你的描述和代码中看,你在使用uniAPP开发小程序和APP,并使用MQTT通讯EMQX Cloud时,遇到了在真机调试时提示“连接异常TypeError: s is not a constructor”。这个错误提示表明在尝试创建一个对象或调用一个函数时遇到了问题,而这个对象或函数并不是预期的构造函数或不存在。在这个场景下,最有可能的问题在于你的MQTT连接部分的代码。

    针对你的问题,我建议按照以下步骤进行排查:

    1. 检查mqtt库导入是否正确:确认你是否正确地导入了mqtt库。在你的代码中看到import mqtt from '@/utils/mqtt4.1.0.js',确保这个路径是正确的并且文件存在。
    2. 检查MQTT库版本与API:确认你使用的MQTT库的版本是否与你的代码兼容。有时API的变更可能导致此类问题。
    3. 检查连接逻辑:在连接逻辑中,确保你在正确的时机和条件下调用MQTT的API。特别是在真机调试时,确保连接的URL和其他参数是正确的。
    4. 检查控制台输出:查看浏览器的控制台输出,看看是否有更详细的错误信息或其他提示。这可能会帮助你定位问题所在。
    5. 尝试简化代码:为了更容易地定位问题,你可以尝试简化代码,只保留最基本的连接和订阅功能,看看是否还会出现同样的问题。一旦基础功能运行正常,再逐步添加其他功能。
    6. 检查权限和网络:确保你的应用有访问网络的权限,并且网络连接是正常的。有时网络问题也可能导致此类错误。

    如果以上步骤都无法解决问题,你可能需要进一步检查你的MQTT服务器配置或与EMQX Cloud的支持团队联系以获取帮助。此外,也可以考虑查看uniAPP的官方文档或社区论坛,看看是否有其他人遇到了类似的问题和解决方案。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月21日
  • 已采纳回答 1月13日
  • 创建了问题 1月3日