y***@qq.com
y***@qq.com
  • 发布:2025-03-19 17:29
  • 更新:2025-03-20 00:21
  • 阅读:68

hbuilderx新版无法连接mqtt

分类:HBuilderX

问题:
我要用微信小程序连接mqtt,在hbuilderx4.15版本可以正常运行;
在hbuilder4.56中就不能用了。

分析:

  • 新版的hbuilderx运行后,微信开发者工具里面发现默认会创建一个wss。
  • 按理说微信小程序一次可以连接两个wss,但是自己的wss连不上。
  • 旧版没有这个问题,旧版没有发现调试用的ws。

分析2:
另外发现hbuilderx新增了日志打印功能,可能是这个添加的ws功能。

其他:

  • 自己的mqtt可能没有连接成功,因为没有发现打印的相关日志.
  • 图中出现的“最多连接两个mqtt”是程序发现连接失败触发的重连,导致微信开发者工具认为“多余2个ws”

求解:
有没有办法关闭这个调试?或者解决这个问题?

export const MQTTA = (host = "broker.emqx.io", port = 8084) => {  
    const clientId = "wxapp_" + Math.floor(Math.random() * 100000)  
    let client = {}  
    const msgHandler = {}  
    return {  
        connect() {  
            const mqttOptions = {  
                keepalive: 30,  
                clean: false,  
                connectTimeout: 5000, // Timeout   
                clientId,  
            }  
            const connectUrl = `${host}:${port}/mqtt`;  
            client = mqtt.connect('wxs://' + connectUrl, mqttOptions);  
            client.on('connect', () => {  
                console.log('MQTT: connect.')  

            });  
            // 重连  
            client.on('reconnect', (msg) => {  
                console.log('MQTT: reconnect', msg)  
            });  
            // 错误  
            client.on('error', () => {  
                console.log('MQTT: error')  
            });  
            // 断开  
            client.on('end', () => {  
                console.log('MQTT: end')  
            });  
            // 掉线  
            client.on('offline', (msg) => {  
                console.log('MQTT: offline', msg)  
            });  
            // 收到消息          
            client.on('message', function(receivedTopic, message) {  
                msgHandler[receivedTopic](message)  
            });  

            // 全局监听是否有关闭mqtt的消息的事件  

        },  
        sub(topic, fns) {  
            msgHandler[topic] = fns  
            client.subscribe(topic, {  
                qos: 0  
            }, function(err) {  
                if (err) {  
                    console.error('Failed to subscribe to topic:', err);  
                } else {  
                    console.log(`Subscribed to topic "${topic}"`);  
                }  
            });  
        },  

        pub(topic, msg) {  
            client.publish(topic, msg, {  
                qos: 0,  
                retain: false  
            }, function(err) {  
                if (err) {  
                    console.error('Failed to publish message:', err);  
                } else {  
                    console.log(`Message published to topic "${topic}":`, msg);  
                }  
            });  
        },  
        close() {  
            client.end(true); // 主动断开连接   
        }  
    }  
}

2025-03-19 17:29 负责人:无 分享
已邀请:
DCloud_heavensoft

DCloud_heavensoft

  • y***@qq.com (作者)

    收到 非常感谢

    2025-03-20 04:13

要回复问题请先登录注册