1

React Native is a cross-platform mobile application development framework launched and open sourced by Facebook. It is a derivative of React in the native mobile application platform and supports both iOS and Android platforms. React Native uses Javascript language, JSX similar to HTML, and CSS to develop mobile applications, so technical personnel familiar with front-end web development can enter the field of mobile application development with little learning, and React Native also provides close to native applications. performance and experience.

MQTT is a lightweight IoT message transmission protocol based on the publish/subscribe model, which can achieve stable transmission on severely constrained hardware devices and low-bandwidth, high-latency networks. It occupies half of the Internet of Things protocols by virtue of its simplicity and ease of implementation, support for QoS, and small packets.

This article mainly introduces how to use MQTT in the React Native project to realize the functions of connecting, subscribing, unsubscribing, and sending and receiving messages between the client and the server.

Create a new React Native project

Here is an example of creating a project named RNMQTTDemo . The development environment is macOS and the application platform is iOS. For the specific process, refer to Setting up the development environment .

After the project is created, in the project root directory environment, execute the following commands to install the required dependencies:

 npm install @react-native-async-storage/async-storage @rneui/base @rneui/themed

Install the MQTT client module

 npm install react_native_mqtt

react_native_mqtt is an MQTT client module used in React Native projects, supporting iOS and Android.

MQTT client module use

Connect to MQTT server

The free public MQTT server provided by EMQ is used here, which is based on EMQ's MQTT IoT cloud platform . The server access information is as follows:

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • Websocket Port: 8083

Create a client instance

 init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  sync : {}
});
const options = {
  host: 'broker.emqx.io',
  port: 8083,
  path: '/testTopic',
  id: 'id_' + parseInt(Math.random()*100000)
};
client = new Paho.MQTT.Client(options.host, options.port, options.path);

Connect to MQTT server

 connect = () => {
    this.setState(
      { status: 'isFetching' },
      () => {
        client.connect({
          onSuccess: this.onConnect,
          useSSL: false,
          timeout: 3,
          onFailure: this.onFailure
        });
      }
    );
  }

Topic subscription

 subscribeTopic = () => {
    this.setState(
      { subscribedTopic: this.state.topic },
      () => {
        client.subscribe(this.state.subscribedTopic, { qos: 0 });
      }
    );
  }

news release

 sendMessage = () =>{
    var message = new Paho.MQTT.Message(options.id + ':' + this.state.message);
    message.destinationName = this.state.subscribedTopic;
    client.send(message);
  }

unsubscribe

 unSubscribeTopic = () => {
    client.unsubscribe(this.state.subscribedTopic);
    this.setState({ subscribedTopic: '' });
  }

run the project

The complete RNMQTTDemo project address: https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-React-Native .

In the project root directory environment, create two new terminal windows and execute the following commands respectively:

 npx react-native start
npx react-native run-ios

After execution, you will see that the application is running in the iOS simulator, and the id of the current client is displayed at the top, as shown below:

MQTT React Native iOS

MQTT connection test

Here , MQTT 5.0 client tool - MQTT X is used for related tests, and a connection named react-native-demo is created. All configuration items use default values. Click the connect button. After the connection is successful, add a subscription with the topic name testTopic. The display is as follows:

MQTT 5.0 客户端工具 - MQTT X

connect

Click the CONNECT button in the APP, and the interface after the connection is successful is displayed as follows, in which the content of the ClientID line at the top turns green, indicating that the connection to the MQTT server has been successfully completed.

连接 MQTT 服务器

Topic subscription

Enter the topic to be subscribed, here is testTopic as an example, and then click the SUBSCRIBE button, the interface after subscription is displayed as follows:

订阅 MQTT 主题

news release

Enter the content of the message to be published, click the PUBLISH button after the input is complete, and the messages received under the current subscription topic will be listed at the bottom. The messages with black background are sent by the current client, and id_67485 is the id of the current client. The interface displays as follows:

MQTT 消息发布

At the same time, under the react-native-demo connection of MQTT X, it also publishes some messages to the topic testTopic , and at the same time, you can also see the messages published to the topic with the client id id_67458, as shown below:

MQTT 消息发布1

unsubscribe

Click the UNSCRIBE button in the APP, and then continue to publish a message with the content { "msg": "hello test" } to the testTopic topic on MQTT X, as shown below:

MQTT 消息发布2

After unsubscribing from the testTopic topic, I did not receive any messages published by MQTT X to the topic { "msg": "hello test" }

MQTT 取消订阅

Summarize

So far, we have completed building an MQTT application using React Native on the iOS platform, realizing functions such as the connection between the client and the MQTT server, topic subscription, sending and receiving messages, and unsubscribing.

With React Native, developers can use standard iOS platform components and develop applications with performance almost similar to native applications; seamless cross-platform allows teams to work faster, while only saving changes during development, i.e. You can see it in action in the iOS Simulator. Efficient, near-native performance, hot reloading and extensive community support make React Native the best choice for many mobile application developers. Combining React Native, MQTT protocol and MQTT cloud service, we can also develop a lot of interesting Innovative applications.

Copyright statement: This article is original by EMQ, please indicate the source when reprinting.

Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-react-native


EMQX
336 声望438 粉丝

EMQ(杭州映云科技有限公司)是一家开源物联网数据基础设施软件供应商,交付全球领先的开源 MQTT 消息服务器和流处理数据库,提供基于云原生+边缘计算技术的一站式解决方案,实现企业云边端实时数据连接、移动、...