我正在尝试第一次使用 mqtt 服务器,并在我也是第一次使用的 React Native 应用程序(使用 Expo)中使用它^^。我现在只是想创建一个简单的组件并存储消息。 为此,我使用命令“mosquitto”启动了本地 mqtt 服务器,并尝试与 MQTTX 进行一些交换,结果成功了。
然后,我尝试在我的 React Native 应用程序中实现一个组件,如下所示:
import React, { useEffect, useState } from 'react';
import { Client, Message } from 'react-native-paho-mqtt';
const MQTTComponent = () => {
const [message, setMessage] = useState(''); // Local state to store MQTT message
useEffect(() => {
// Create an instance of the MQTT client
const client = new Client({
uri: 'mqtt://127.0.0.1:1883',
clientId: 'testClient',
});
// Function to handle received MQTT messages
const handleMessage = (message) => {
console.log(`Received message on topic ${message.destinationName}: ${message.payloadString}`);
setMessage(message.payloadString); // Update the 'message' variable
};
// Establish the connection to the MQTT server
client.connect()
.then(() => {
console.log('Connected to MQTT server');
// Subscribe to an MQTT topic
client.subscribe('topic');
})
.catch((error) => {
console.error('MQTT connection error:', error);
});
// Configure the event handler for MQTT messages
client.onMessageArrived = handleMessage;
// Return a cleanup function to unsubscribe and disconnect on unmount
return () => {
client.unsubscribe('topic'); // Unsubscribe from the MQTT topic
client.disconnect(); // Disconnect from the MQTT server
};
}, []); // The empty array means this code runs only once on component creation
};
export default MQTTComponent;
但是,我收到错误:
Error: AMQJS0013E Invalid argument string for uri.
我尝试更改 uri,但我总是遇到相同的错误,我真的需要一些帮助来理解这一点。
提前非常感谢您。
您遇到的错误消息“错误:AMQJS0013E uri 的参数字符串无效”通常表示您在创建 MQTT 客户端时提供的 URI 存在问题。在您的代码中,您已将 URI 指定为
'mqtt://127.0.0.1:1883'
,这对于在默认端口上运行的本地 MQTT 服务器来说似乎是正确的。
这里有一些需要检查和尝试的事情:
Mosquitto 配置:确保本地 Mosquitto MQTT 服务器已启动并正在运行,并且正在侦听指定端口(默认为 1883)。您可以通过在终端中运行
mosquitto -v
来检查其状态。
服务器地址:如果您在物理设备或模拟器上运行 React Native 应用程序,请确保您的设备可以访问运行 Mosquitto 的本地计算机。如果您在物理设备上进行测试,则手机和您的开发计算机应该位于同一本地网络上。如果您使用模拟器,请确保它可以到达本地服务器。
客户端 ID:每个 MQTT 客户端的
clientId
应该是唯一的。确保您没有对多个客户端使用相同的 clientId
。
协议:确保
react-native-paho-mqtt
库支持您的 Mosquitto 服务器使用的 MQTT 协议版本。 MQTT 有多个版本(例如 3.1.1、5.0),并且库兼容性可能会有所不同。
这是代码的稍微修改版本,并进行了一些额外的调试:
import React, { useEffect, useState } from 'react';
import { Client, Message } from 'react-native-paho-mqtt';
const MQTTComponent = () => {
const [message, setMessage] = useState('');
useEffect(() => {
const client = new Client({
uri: 'mqtt://127.0.0.1:1883',
clientId: `testClient-${Math.random().toString(36).substr(2, 9)}`, // Generate a unique clientId
});
const handleMessage = (message) => {
console.log(`Received message on topic ${message.destinationName}: ${message.payloadString}`);
setMessage(message.payloadString);
};
client.connect()
.then(() => {
console.log('Connected to MQTT server');
client.subscribe('topic');
})
.catch((error) => {
console.error('MQTT connection error:', error);
});
client.onMessageArrived = handleMessage;
return () => {
client.unsubscribe('topic');
client.disconnect();
};
}, []);
return (
<div>
<p>MQTT Message: {message}</p>
</div>
);
};
export default MQTTComponent;
如果您在检查上述几点后仍然遇到问题,请提供有关您的开发环境的更多详细信息以及任何相关的错误消息,我将尽力进一步帮助您。