I'm trying to set a simple communication between an ESP32 as client, and a Java server running on my Windows PC.
I have this python code for the server that works:
import socket
s = socket.socket()
s.bind(('192.168.1.246', 8090 ))
s.listen(0)
while True:
client, addr = s.accept()
while True:
content = client.recv(32)
if len(content) ==0:
break
else:
print(content)
print("Closing connection")
client.close()
But my whole software is written in java, so I need to write something like that in java. Here is my Java Code for the Server:
Thread serverThread = new Thread(new Runnable() {
@Override
public void run() {
try{
ss = new ServerSocket(8090);
s = ss.accept();
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
clientMessage = (String) din.readUTF();
while(!clientMessage.equals("stop")){
clientMessage = din.readUTF();
serverMessage = "This is the message from the server";
dout.writeUTF(serverMessage);
dout.flush();
}
din.close();
s.close();
ss.close();
}catch(Exception e){
e.printStackTrace();
//System.out.println(e);
}
}
});
serverThread.start();
My Arduino code for the ESP32 is:
include <WiFi.h>
const char* ssid = "myssid";
const char* password = "mywifipass";
const uint16_t port = 8090;
const char * host = "192.168.1.246";
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("...");
}
Serial.print("WiFi connected with IP: ");
Serial.println(WiFi.localIP());
}
void loop()
{
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection to host failed");
delay(1000);
return;
}
Serial.println("Connected to server successful!");
client.print("Hello from ESP32!");
Serial.println("Disconnecting...");
client.stop();
delay(10000);
}
If I use python server everything works great, but if I use Java server I can establish the connection between them and I get an EOFExcepion at server line:
clientMessage = (String) din.readUTF();
readUTF() API's says:
Throws:EOFException - if this input stream reaches the end before reading all the bytes.
So, what's going on here and how can I solve it?
I solved the issue replacing
clientMessage = (String) din.readUTF();
with:
byte[] myMessage = din.readAllBytes();
clientMessage = translate(myMessage);
where translate() function is:
private static String translate(byte[] word)
{
String translatedMessage = "";
for(int i=0; i<word.length; i++) {
translatedMessage = translatedMessage + (char) word[i];
}
return translatedMessage;
}