WebSocket Connection Issue: Works in Expo Go but Fails in Production
Published: 2024-06-01 17:15:28

I'm facing an issue with my Expo React Native app where the WebSocket connection works perfectly when running in Expo Go (development mode), but fails to connect when the app is installed on a smartphone in production mode.

Here are the details: The app uses WebSocket to communicate with an ESP32 device over a local Wi-Fi network, routed by the same smartphone where I run the app. In development mode using Expo Go, the WebSocket connection is stable and data is transmitted without any problems. When the app is built and installed on a smartphone (Android), the WebSocket does not connect. The smartphone is acting as the access point for the Wi-Fi network, and the ESP32 connects directly to it. The ESP32 is the Websocket server and the app connect trought the ESP32 IP and port.

I've checked for any potential issues with wifi enable but couldn't pinpoint the problem.

Has anyone encountered similar issues or have any insights on what might be causing the WebSocket connection to fail in production? Any help or suggestions would be greatly appreciated!

app.json

{
  "expo": {
    "name": "appLidar",
    "slug": "appLidar",
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/icon.png",
    "userInterfaceStyle": "light",
    "splash": {
      "image": "./assets/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "ios": {
      "supportsTablet": true
    },
    "android": {
      "permissions": ["INTERNET", "ACCESS_NETWORK_STATE"],
      "adaptiveIcon": {
        "foregroundImage": "./assets/adaptive-icon.png",
        "backgroundColor": "#ffffff"
      },
      "package": "com.WebSilos.appLidar"
    },
    "web": {
      "favicon": "./assets/favicon.png"
    },
    "extra": {
      "eas": {
        "projectId": "5f51a79e-ae14-4aeb-9de3-300395e7bd48"
      }
    }
  }
}
app.js

import { StatusBar } from "expo-status-bar";
import { Pressable, StyleSheet, Text, View } from "react-native";
import { useEffect, useState } from "react";

let lastMsg = "Mensagem Inicial";

function connectWebSocket() {
  const ws = new WebSocket(`ws://192.168.43.12:81`);
  lastMsg = "Iniciando WebSocket";
  console.log(lastMsg);

  ws.onopen = (event) => {
    lastMsg = "Sensor conectado!" + event.data;
    console.log(lastMsg);

    // connectLidar = true;
    // extConnected !== undefined ? extConnected(connectLidar) : "";
  };

  ws.onmessage = async function (event) {
    lastMsg = "Mensagem recebida: " + event.data;
    console.log(lastMsg);
    // const lidarData = event.data.split(",");
    // if (lidarData[0] === "B0") {
    //   log.push("Botao alterado: " + lidarData[1]);
    //   if (lidarData[1] === "true") {
    //     extStart();
    //   }
    // } else {
    //   const lidarFiltered = await bufferReceive(lidarData);
    // }
  };

  ws.onclose = function (event) {
    lastMsg = "Conexão fechada, código:" + event.code;
    console.log(lastMsg);
    // connectLidar = false;
    // extConnected !== undefined ? extConnected(connectLidar) : "";
    // // Tentar reconectar após 30 segundos
    // setTimeout(connectWebSocket, 30000);
  };
}

// Iniciar a conexão WebSocket
connectWebSocket();

export default function App() {
  const [mensagem, setMensagem] = useState("Local para mensagens recebidas");

  const handlePress = () => {
    setMensagem(lastMsg);
  };

  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <Pressable onPress={handlePress}>
        <Text>{mensagem}</Text>
      </Pressable>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});
package.json

{
  "name": "applidar",
  "version": "1.0.0",
  "main": "expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "expo": "~51.0.8",
    "expo-status-bar": "~1.12.1",
    "react": "18.2.0",
    "react-native": "0.74.1",
    "expo-dev-client": "~4.0.15"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0"
  },
  "private": true
}