My proof of concept for a simple socket between Android and esp8266 works only 50%.
I send one message from Android to esp8266, which is received normally, but from esp8266 to android is not, and ends in having java.io.EOFException in android side and Timeout (as seen in code below) for esp8266 side.
I provide the related part of code to be brief, if needed I will post all.
Android:
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
String msgReply = "Android server is alive!";
dataOutputStream.writeUTF(msgReply);
dataOutputStream.flush();
message = dataInputStream.readUTF();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
msg.setText(message);
}
});
}
ESP8266 side:
String cmd = "Hello from NodeMCU";
Serial.print("send to server: ");
Serial.println(cmd);
client.print(cmd);
client.flush();
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
while(client.available()){
String line = client.readStringUntil('!');
Serial.print(line);
}
I've tried whatever came to my mind, switching to writing char using client.write('h'), etc. and nothing works.
Please point me to some working direction.
I send one message from Android to esp8266, which is received normally,. Hard to believe. as the leading utf bytes would give you a corrupted string.client.print(cmd);should beclient.print(cmd + "\n");if you decide to work with lines.