Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Dont connect to centrifuge react-native android build #242

Closed
VictorPulzz opened this issue Aug 3, 2023 · 6 comments
Closed

Dont connect to centrifuge react-native android build #242

VictorPulzz opened this issue Aug 3, 2023 · 6 comments

Comments

@VictorPulzz
Copy link

VictorPulzz commented Aug 3, 2023

Describe the bug
Hey guys! I connected centrifuge to rn application , but I'm faced with problem on android device. When I run application in develop mode, sockets working cool. But after created build, my application dont connect to centrifuge and I got this error

{"type":"transport","error":{"code":2,"message":"transport closed"},"transport":"websocket"} 

Although I got token and this code working on ios (simulator / real device) and only android dev mode

To Reproduce code

import { useSwitchValue } from '@appello/common/lib/hooks';
import { Centrifuge } from 'centrifuge';
import { lowerCase } from 'lodash';
import React, { useEffect } from 'react';

import { useAppDispatch, useAppSelector } from '~/core/store';
import { selectIsAuth, selectUser, useLazyGetWsTokenQuery } from '~/entities/User';
import { ENV, WS_URL } from '~/shared/config';

import { useLogs } from './log';
import { CentrifugePublicationContextEnum, CentrifugePublicationContextType } from './types';

export const CentrifugeWorker = () => {
  const logs = useLogs();
  const user = useAppSelector(selectUser);
  const isAuth = useAppSelector(selectIsAuth);
  const dispatch = useAppDispatch();
  const [getToken] = useLazyGetWsTokenQuery();
  const { value: initialize, on: onInitialize } = useSwitchValue(false);

  const handlePublicationData = (
    content: CentrifugePublicationContextType['data']['content'],
    type: CentrifugePublicationContextEnum,
  ) => {
    switch (type) {
      default:
    }
  };

  useEffect(() => {
    if (initialize) return;

    if (user && isAuth) {
      onInitialize();

      logs('IS AUTH', JSON.stringify({ user, isAuth }));

      const centrifuge = new Centrifuge(WS_URL, {
        getToken: async () => {
          logs('GET TOKEN START', JSON.stringify(user));
          if (!user) return '';
          const data = await getToken().unwrap();
          logs('GOT TOKEN', JSON.stringify(data));
          return data;
        },
      });

      centrifuge.on('error', ctx => {
        logs('onError', JSON.stringify(ctx));
      });

      const subscription = centrifuge.newSubscription(`test_${lowerCase(ENV)}:user#${user.id}`);
      subscription
        .on('publication', ctx => {
          const context = ctx as CentrifugePublicationContextType;
          handlePublicationData(context.data.content, context.data.type);
          logs('Publication', JSON.stringify(ctx));
        })
        .on('subscribed', ctx => {
          logs('Subscribed', JSON.stringify(ctx));
        })
        .on('unsubscribed', ctx => {
          logs('Unsubscribed', JSON.stringify(ctx));
        })
        .subscribe();

      centrifuge.connect();
    }
  }, [user, initialize, onInitialize, getToken, isAuth, logs, handlePublicationData]);

  return <></>;
};

Expected behavior
Socket will be working

Versions

  • OS: MasOS m1 Ventura: 13.4.1
  • React-Native: ^0.71.8
  • React: 18.2.0
  • Centrifuge client version: ^4.0.1
  • Server version: 5.0.1

Additional context
Add any other context about the problem here.

@FZambia
Copy link
Member

FZambia commented Aug 3, 2023

Hello @VictorPulzz

Could you provide step-by-step guide to reproduce the problem locally without your app specifics (i.e. provide a fully-working reproducer)? Also, please include step-by-step instructions how to build and run the app on Android to see the issue.

@VictorPulzz
Copy link
Author

@FZambia Okay let my time, I prepare example test repo with my env

@FZambia
Copy link
Member

FZambia commented Aug 3, 2023

Thanks, waiting - also check out server logs with "log_level": "trace" in configuration - probably you will see something interesting. I am personally never tried building an app for Android with React Native - that's why I need help to reproduce.

@chetannn
Copy link

I am getting the same error message transport closed with error code 2. I also tried setting "log_level": "trace" on the config file but didn't see any logs on the server. It works during the development though on android and ios (using simulator) using the same server credential. I haven't tried it with IOS on a preview build. It fails after the EAS build.

@chetannn
Copy link

chetannn commented Jan 3, 2025

I am getting the same error message transport closed with error code 2. I also tried setting "log_level": "trace" on the config file but didn't see any logs on the server. It works during the development though on android and ios (using simulator) using the same server credential. I haven't tried it with IOS on a preview build. It fails after the EAS build.

We investigated the problem. Basically, problem is with android not allowing to communicate over http or ws. https or wss works on android preview builds. To run websocket over http, we did following steps:

  1. Setting android permission in app.json or app.config.ts
{
 name: 'xxx',
 android: {
    package: 'com.org.app',
    permissions: ['INTERNET']
  }
}
  1. Install expo-build-properties plugin and setting build property usesCleartextTraffic set to true inapp.jsonor app.config.ts
{
  "expo": {
    "plugins": [
      [
        "expo-build-properties",
        {
          "android": {
            "usesCleartextTraffic": true
          },
          "ios": {
          }
        }
      ]
    ]
  }
}

For bare react-native. We can edit AndroidManifest.xml directly from android directory.

@FZambia
Copy link
Member

FZambia commented Jan 30, 2025

@chetannn many thanks for investigating and posting the solution. I added a note about this to README in #309

@FZambia FZambia closed this as completed Jan 30, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants