簡體   English   中英

如何在 React-Native 中連接到 MQTT 代理?

[英]How to connect to an MQTT broker in React-Native?

我正在嘗試將 MQTT 集成到我的應用程序中。 我正在閱讀這篇文章,但由於使用過時的 React Native MQTT 庫或我的代碼錯誤,我無法連接到代理。 如何成功連接到代理?

import init from 'react_native_mqtt';
import { AsyncStorage } from 'react-native';

init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  reconnect: true,
  sync : {
  }
});

const client = new Paho.MQTT.Client(
  "m23.cloudmqtt.com", 
  18628,
  "clientID-" + parseInt(Math.random() * 100)
);

client.connect({ 
  useSSL: true,
  userName: "username",
  password: "password"
});

function onConnect() {
  client.subscribe("topic");
}

在這里回答太晚了,但我希望這能幫助其他人,因為我花了 3 天的時間才弄明白。 問題是您使用的庫按承諾工作,但它需要網絡套接字,我並不是說現在您必須實現網絡套接字,但現在您必須為您的代理使用網絡套接字端口。

For Example ::
Broker : broker.hivemq.com

Port :
1) 8000 (for web sockets)
2) 1883 (for TCP connection, pretty sure you'll be using this in your IOT)

所以你的客戶端創建代碼現在看起來像這樣 ::


    const client = new Paho.MQTT.Client(
      "broker.hivemq.com", 
      8000,
      "clientID-" + parseInt(Math.random() * 100)
    );

閱讀有關HiveMQ 公共代理及其Web 套接字瀏覽器客戶端的更多信息,以便您輕松測試 MQTT 發布和訂閱!

不僅如此,您使用的AsyncStorage已棄用 所以改用這個

有了新的 AsyncStorage 和代理的 Web-Sockets 端口,您就可以開始了! 或者至少對於存儲和連接部分:)

這是我的代碼,以便更好地理解::


    import AsyncStorage from '@react-native-async-storage/async-storage';
    import init from 'react_native_mqtt';
    
    init({
      size: 10000,
      storageBackend: AsyncStorage,
      defaultExpires: 1000 * 3600 * 24,
      enableCache: true,
      reconnect: true,
      sync : {}
    });
    
    function onConnect() {
      console.log("onConnect");
      client.subscribe('reactnative/testmqtt');
    }
    
    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {
        console.log("onConnectionLost:"+responseObject.errorMessage);
      }
    }
    
    function onMessageArrived(message) {
      var x = "\nTopic : "+message.topic+"\nMessage : "+message.payloadString;
      console.log(x);
    }
    
    const client = new Paho.MQTT.Client('broker.hivemq.com', 8000, 'uname');
    client.onMessageArrived = onMessageArrived;
    client.connect({ onSuccess:onConnect, useSSL: false });
    client.onConnectionLost = onConnectionLost;

PS 不要使用 SSL,因為由於某種原因它不起作用 0_o

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM