stevenjin 2024-12-26 23:41 采纳率: 96.8%
浏览 31
已结题

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

1.uniAPP开发小程序和APP,使用MQTT通讯EMQX Cloud。
2.用网页h5调试通收到订阅消息,但在手机上真机运行时,提示:
连接异常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条回答 默认 最新

  • 关注

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

    这个问题似乎与代码和程序运行有关,因此我会尝试给出一些可能的解决方案。

    根据你给出的错误信息 "TypeError: s is not a constructor",这个错误可能意味着你正在试图使用一个未定义或者不是构造函数的变量作为构造函数。这可能是因为你的代码中有些部分未正确地初始化或者引入相关的库或模块。针对这个问题,我建议你按照以下步骤进行检查和修复:

    1. 检查你的mqtt库是否已经正确安装并导入。确认你的项目中是否有一个名为mqtt的模块,并且你正确地在你的脚本中导入了它。如果你的mqtt库是从其他地方复制的,而不是通过npm或yarn安装的,可能会出现这种情况。尝试重新安装或更新该库。

    在JavaScript中,导入模块的标准方式是使用 require(CommonJS)或 import(ES6)。对于npm安装的库,它们通常会有一个index.js文件作为入口点,你可以在项目中通过这个名字导入。请确认你的mqtt库是否有正确的入口点。例如,你可能需要将导入语句更改为 import mqtt from '@/utils/mqtt'(假设你的mqtt库在项目的utils目录下)。如果库名正确,但仍然出现错误,请检查该库是否包含你尝试使用的MQTT客户端功能。

    1. 检查你的MQTT连接配置是否正确。特别是URL部分,根据你的环境和设备(真机/模拟器),你可能需要使用不同的协议(例如ws://对于Web套接字或wxs://对于微信小程序)。确认你的协议和主机名是正确的。你可以尝试打印出你的连接字符串以确认其正确性。此外,确认你的端口号是否正确并且服务器正在监听该端口。对于微信小程序,你可能需要使用特定的协议前缀(如wxs://)。请确保你使用了正确的协议前缀并且服务器支持该协议。

    如果以上步骤都不能解决问题,可能需要进一步检查你的代码以确定问题所在。请确保所有的函数和变量都已正确声明和初始化,特别是你在使用它们之前是否已正确创建MQTT客户端实例。同时检查你的错误处理代码是否正常运行,并能够捕获所有可能的错误情况。

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

报告相同问题?

问题事件

  • 系统已结题 1月11日
  • 已采纳回答 1月3日
  • 创建了问题 12月26日