Search code examples
androidreact-nativewebsocketnats.io

Timeout error in nats client connectivity for react native | Android ONLY


I am using Nats Client in my mobile application to connect to Nats server and publish/subscribe. For the iOS, same piece of code snippet is just working fine (Also the same snippet works in my separate project of react js), but when I try to connect the same through Android App, I am not able to connect and getting :

[NatsError: TIMEOUT] (It is being consoled from the catch block of the snippet below, "REASON>>>")

Here is the code snippet I am using in order to connect to NATS server: ` serverConnectionPromise = new Promise<NatsConnectionImpl | null>((resolve) => {

      connect({
        servers: server, //My Server URL i.e. wss://url.to.server/ws
        noEcho: true,
        token: sdjfhjsERDFDf, //A String is being used here
      })
        .then((nc: NatsConnectionImpl) => {
          resolve(nc);
        })
        .catch((reason) => {
          console.log("REASON>>>", reason);
          resolve(null);
        })
    });`

I tried several solutions from the relevant questions and articles like allowing the Internet permission in .xml file of android and app.json, disable NetworkFlipper, adding a "/" at last in URL of socket (i.e. wss://url.to.server/ws/ which results into 404)

For Nats, I am using a nats.js file as the NPM package is causing an issue while preparing the Android build (That's a separate and a big issue but I can provide a detail of that as well if required), the version of Nats I am using is 1.11.2 - nats.ws

Let me know if I missed any details which is needed to debug it more. Thanks


Solution

  • You can use the nats.ws client in React Native by following a few setup steps.

    The nats.ws package requires a few browser and Nodejs APIs unavailable within the React Native JS runtime by default. You can use polyfills to make these APIs available in your app's context.

    The setup steps and an example project can be found here.