Search code examples
javac++socketsesp32

Recieve Data from ESP32 Socket Server with Android


I'm trying to recieve data from my ESP32 with an Android App. Sending data from my phone isn't a problem. I just don't get anything. It doesn't show an exception and also not a msg. My code so far:

//In the onCreate method:
Connection connection = new Connection();
connection.execute();

//The Connection:
class Connection extends AsyncTask<Void,Void,Void> {
        String msg;

        @Override
        protected Void doInBackground(Void...params){
            try{
                client = new Socket("ESP32-1",80);
                input = new BufferedReader(new InputStreamReader(client.getInputStream()));
                System.out.println(input.readLine());
            }catch (UnknownHostException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }

            while (true) {
                try {
                    msg=input.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(msg);
            }
        }
    }

Permissions:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

ESP32(in Arduino IDE):

#include <WiFi.h>

const char* ssid="Jack-2.4";
const char* password="QayWsxEdcRfv123456#"; 

WiFiServer server(80);

void setup() {
  
  //Server
  Serial.begin(115200);
  Serial.println("start");
  
  delay(1000);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
 
  Serial.println("Connected to the WiFi network");
  Serial.println(WiFi.localIP());
 
  server.begin();
}

void loop() {
  WiFiClient client = server.available();
 
  if (client) {
    Serial.println("Client connected");
 
    while (client.connected()) {
      client.write('A');
      delay(500);
    }
  }
}

I checked the ESP32 Code if it writes and it does send the messages. Is there anything i missed?


Solution

  • Your Android code is calling input.readLine() but your ESP32 code is only sending a single character, not a line, so of course the client never shows any input. Try sending a line.

          client.writeln('A');
    

    or

          client.write("A\n");
    

    The string in the second version might need to be "A\r\n"; I'm not 100% clear what Android will consider to be a line terminator.