Enviar archivo de audio/imagen Servidor Arduino Ethernet + Cliente Java por TCP

Vale, despues de realizar la copia de un archivo con exito. Me tiré a la piscina para programar el cliente en java (android).

Tengo el protocolo implementado, pero tengo problemas con los tipos de variables entre arduino y java.

Resumiendo un poco el codigo, una vez hecha la conexión el cliente se queda a la espera de que le llegue el tamaño del primer buffer que enviará arduino.
Una vez recibido el tamaño, leo los datos y los almaceno en un buffer al que se le irán añadiendo todos los datos del archivo que más tarde, guardo en la SD del movil.

El problema está, en que por ejemplo, envio un tamaño = 500 y java lo interpreta como un numero totalmente distinto (8499834 por ejemplo). He utilizado diferentes formas para enviar: client.write(500), cliente.print(500)...

Y ya no se que hacer para que se entiendan el uno con el otro.

Si alguien me pudiera ayudar le estaría muy agradecido. Adjunto los dos codigos por si alguien ve algun error.

Gracias otra vez.

codigo arduino

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>



File FileFlor;
byte buffer[500];
int TAM_MAX = 500;
int zero = 0;

// Introducir la dirección MAC, IP y numero de PUERTO para el SERVER

byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // Ya se verá
IPAddress serverIP(192,168,1,128); // Ya se verá
int serverPort=8888; // Ya se verá

// Iniciamos la libreria del server ETHERNET
EthernetServer server(serverPort);

void setup()
{

  Serial.begin(9600);
  // Iniciamos la conexion ethernet y el server:
  Ethernet.begin(mac, serverIP);
  server.begin();
  Serial.println("Server en MARCHA");//log
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
  pinMode(10, OUTPUT);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
}

void loop()
{
  // Escucha de clientes
  EthernetClient client = server.available();
  int tam;
  if (client) {

    //Declaro la variable string que contendrá lo que nos envie el cliente
    //String clientMsg ="";
    while (client.connected()) {
      if (client.available()) {
        FileFlor = SD.open("Archivo2.txt");

        if (FileFlor) {
          Serial.print("opening the img Flor.jpg..");
          Serial.println("done.");
        } 
        else {
          Serial.println("error opening Flor.jpg");
        } 


        if (FileFlor) {
          
          int i = 0;
               
          while (FileFlor.available()>0) {
            buffer[i] = FileFlor.read();
            
            Serial.println(i);
            
            //Envio tamaño
            client.print(TAM_MAX,DEC);
            
            
            if(i==TAM_MAX-1){ 
              
              //envio buffer con datos        
              client.write(buffer,TAM_MAX);
              Serial.println("Transfering to client..... ");  
              i=-1;
            }
            i++;
          }
          
          
          
          if(i>0){
      
            client.print(i);      
            for(int a=0; a<i ; a++){
              
              client.write(buffer[a]); 
            }       
          }
          //Enviamos que el tamaño es 0, para que se salga del bucle en el cliente.
          client.write(zero);
        }

        Serial.println("Done Transfer");    
        FileFlor.close();
      } 
    }
  }
  //Delay de espera para que el cliente reciba los datos
  delay(1);
  //Cerramos la conexión
  client.stop();
}

codigo JAVA

 public void onClick(View v) {
                              
                   try {
                     
                     Socket cs = new Socket("192.168.1.128", 8888);                                          
                     DataOutputStream Out = new DataOutputStream(cs.getOutputStream());
                     DataInputStream In = new DataInputStream(cs.getInputStream());
                     
                     Out.writeUTF(Lista.get(ListaObjetos.getCheckedItemPosition()));           
                     
                     //Recepcion de archivo en paquetes de tcp max bytes
                     ArrayList<Byte> buffer;
                    
                     buffer = new ArrayList<Byte>();
                     byte[] data;
                     
                    //Leo tamaño
                     int tam=In.readInt();
                                       
                     while(tam>0){                         
                        data = new byte[tam];
                        In.read(data);
                        for(int i=0; i<tam;i++){
                        buffer.add(data[i]);
                        }
                        tam=In.readInt();                        
                     }
                    
                     
                     In.close();
                     Out.close();
                     cs.close();
                     byte[] archivo =new byte[buffer.size()];
                     for(int i=0; i<buffer.size();i++){
                        archivo[i]=buffer.get(i);
                     }
                                                              
                     save_file(archivo,Lista.get(ListaObjetos.getCheckedItemPosition()));
                     
                 } catch (IOException ex) {
                     toastShow(ex.toString());
                     Logger.getLogger(PFC.class.getName()).log(Level.SEVERE, null, ex);
                 }              
                   
                 
                 
             }