Search code examples
react-nativesocketsexpoio-socket

Expo React Native application inside of iOS Simulator keeps reconnecting using socket.io


The stack is atm VueJS, React Native using Expo, and NestJS for the backend. For convenience, this repo contains a working example of VueJS and NestJS parts. The connection from the React Native side (simplified version) is implemented like this:

export const useSubscribeToWebsocket = (token: string) => {
  const { socketUrl } = usePlatform()

  useEffect(() => {
    console.log('open')
    const socket = io(socketUrl)

    socket.on('connect', () => {
      console.log('connect')
      socket.send(JSON.stringify(authenticate(token)))
    })

    socket.on('error', (error: any) => {
      dlog('error connection=> ', error)
    })

    socket.on('event', (socketEvent: any) => {
      console.log('event ', socketEvent)
    })

    return () => {
      socket.close()
    }
  }, [token])

  return null
}

The gateway (socket server) looks pretty straightforward:

@WebSocketGateway()
export class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('AppGateway');

  @SubscribeMessage('msgToServer')
  handleMessage(client: Socket, payload: string): void {
    this.server.emit('msgToClient', payload);
  }

  afterInit(server: Server) {
    this.logger.log('Init');
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`);
  }

  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`Client connected: ${client.id}`);
  }
}

The problem is that while the mobile client connects only once (the useEffect hook is called one single time, no other logs except open), handleConnection keeps logging clients with different ids being connected. connect is also never logged on the RN side, so I suppose it never connects. I tested it with VueJS client, and it connects only once (works fine on backend as well), everything works.

Is it a problem related to the simulator only? Is there a way to fix it?


Solution

  • For now, downgrading to 2.1.1 from 3.0.4 fixed the issue.