React Native使用react_native_mqtt连接MQTT失败报AMQJS0007E如何解决
问题根因与解决方案
1. 现有代码语法错误
你当前onConnect方法中存在解构错误:const { client } = this.state.client; 写法错误,this.state中已经直接存储了client对象,直接通过const { client } = this.state; 取值即可,该错误会导致连接成功后订阅逻辑失效,但不是连接失败的核心原因。
2. 连接失败核心原因(对应AMQJS0007E报错)
react_native_mqtt底层基于Paho MQTT JS库实现,仅支持WebSocket协议的MQTT连接,你使用的80端口是MQTT over TCP的默认端口,不是WebSocket端口,MQTT over WS的默认非SSL端口一般为8083,SSL端口为8084,需要确认你的MQTT服务端已开启WebSocket端口,且配置了正确的WS访问路径(多数服务端默认WS路径为/mqtt)。- Android 9及以上系统默认禁止明文HTTP请求,你配置了
useSSL: false走明文传输,需要在AndroidManifest.xml的application节点添加android:usesCleartextTraffic="true"配置。 - 模拟器访问本地服务端配置错误:如果你的MQTT服务端部署在本地,Android模拟器不能用
127.0.0.1访问本地服务,需要填10.0.2.2;真机需要和服务端处于同一局域网,填服务端的局域网IP。 - 客户端ID重复:如果多设备/多连接使用了相同的clientID,服务端会主动踢掉旧连接,导致连接失败,建议给clientID添加随机字符串后缀保证唯一性。
- 若使用iOS设备调试,需要在Info.plist的
NSAppTransportSecurity配置下新增NSAllowsArbitraryLoads = true,允许明文流量请求。
3. 修正后代码示例
constructor(){ super(); this.onMessageArrived = this.onMessageArrived.bind(this) this.onConnectionLost = this.onConnectionLost.bind(this) this.onConnect = this.onConnect.bind(this) // 注意:host不要带http/https前缀,port填MQTT over WS端口,比如8083 const clientID = 'rn_' + Math.random().toString(16).substring(2, 8) // 生成唯一clientID const client = new Paho.MQTT.Client(host, Number(port), "/mqtt", clientID); // 第三个参数为WS路径,根据服务端配置调整 client.onMessageArrived = this.onMessageArrived; client.onConnectionLost = this.onConnectionLost; client.connect({ onSuccess: this.onConnect, useSSL: false, userName: "user", password: "pass", onFailure: (e) => {console.log("连接失败详情:", e)}, // 新增失败日志方便排查 timeout: 10, // 10秒超时,不需要等几分钟才返回错误 keepAliveInterval: 30 }); this.state = { message: [''], client, messageToSend:'', isConnected: false, }; } onConnect = () => { const { client } = this.state; // 修正解构错误 console.log("Connected!!!!"); client.subscribe(topic, {qos: 0}, (err) => { if(err) console.log('订阅失败:', err) else console.log('subscribe success topic1'); }); this.setState({isConnected: true, error: ''}) };
4. 前置排查验证
先使用MQTT桌面工具(如MQTTX),选择WebSocket协议,填入你使用的host、端口、WS路径、用户名密码,确认可以正常连接订阅,先排除服务端配置、端口不通、账号密码错误等问题。
内容的提问来源于stack exchange,提问作者Keltouma Indtaher
相关产品推荐
相关产品推荐

