A server in java, sends from a Server socket a byte array, this byte array contains text (utf-8) with the next format:
- first 4 bytes: an int with the number of bytes of the text
- next n bytes: each byte represents a char.
So i am using "WiFiClient" from the "ESP8266WiFi.h" library (it should be the same as "WiFi.h" library), WifiClient has a method to receive a byte using the read() method, the problem is that i am unable to read correctly the int (first four bytes) or transform the bytes into int value. So i will be very gratefull if you help me with that:
Java (Server) simplified code:
String respuestaServer="RESPUESTAS DEL SERVER";
DataOutputStream out=new DataOutputStream(sock.getOutputStream());
out.writeInt(respuestaServer.getBytes(StandardCharsets.UTF_8).length);
out.write(respuestaServer.getBytes(StandardCharsets.UTF_8));
out.flush();
Arduino (Client) code to receive and interpret the byte array (the objective of this code is transform the bytes into a String):
String recibirInfo() {
//TRYING TO READ FIRST FOUR BYTES
byte bytesSizeMsj[4];
for (int i = 0; i < sizeof(bytesSizeMsj); i++) {
bytesSizeMsj[i] = client.read();
Serial.print("BYTE: "+bytesSizeMsj[i]);
}
//TRYING TO TRANSFORM THE FOUR BYTES INTO AN INT
int sizeMsj = int((unsigned char)(bytesSizeMsj[0]) |
(unsigned char)(bytesSizeMsj[1]) |
(unsigned char)(bytesSizeMsj[2])|
(unsigned char)(bytesSizeMsj[3]));
Serial.println(sizeMsj);
char charArray[sizeMsj];
//TRYING TO READ THE REST OF THE MESSAGE
for (int i = 0; i < sizeof(charArray); i++) {
charArray[i] = client.read();
}
//TRYING TO TRANSFORM THE BYTE ARRAY INTO A STRING
String msj=charArray;
return msj;
}