推荐开源项目:React Native Mqtt - 轻松集成 MQTT 协议到你的React Native应用
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import mqtt from 'react-native-mqtt';
const options = {
host: 'mqtt://broker.hivemq.com',
port: 8000,
clientId: 'mqtt-react-native-client-id',
username: 'your_username', // optional
password: 'your_password', // optional
};
const MqttComponent = () => {
useEffect(() => {
const client = mqtt.connect(options);
client.on('connect', () => {
console.log('Connected to MQTT server');
client.subscribe('your/topic');
});
client.on('message', (topic, message) => {
console.log(`Received message on ${topic}: ${message.toString()}`);
// 处理接收到的消息
});
return () => {
// 清理操作,比如断开连接
client.end();
};
}, []);
return (
<View>
<Text>MQTT Client connected</Text>
</View>
);
};
export default MqttComponent;
这个代码示例展示了如何在React Native应用中使用react-native-mqtt
库来连接MQTT服务器,订阅一个主题,并接收消息。这个例子使用了React Native的函数组件和Hooks API,并在组件挂载时建立MQTT连接,在卸载时清理资源。
评论已关闭