Problems in remote threads synchronization in two Java Android applications

44 views Asked by At

I have a problem with syncing two android apps exchanging data via TCP Socket using OutputStream and InputStream. By trying the two apps on the same smartphone, the data is sent and read in the correct order and all works fine. But if the devices on which the two apps run are different, the data are sent (or read) in a different order than expected and therefore I cannot use them for subsequent operations.

This is the part of the sender thread that sends the data, where "output_client" is an instance of OutputStream:

for(int i=0; i<4; i++){

       byte[] cert_byte = certs[i].getEncoded();
       output_client.write(ByteBuffer.allocate(4).putInt(cert_byte.length).array());
       output_client.flush();

       output_client.write(cert_byte);
       output_client.flush();
}

This is the part of the receiver thread that receives the data, where "inputStream" is an instance of InputStream:

for(int i=0; i<4; i++){

    inputStream.read(lenByte);
    len = ByteBuffer.wrap(lenByte).getInt();
    byte[] certByte = new byte[len];

    inputStream.read(certByte);

    [...]
}

As seen particularly in the receiver, the order in which data is read from the inputStream is important. My problem is that the second inputStream.read() doesn't read the expected data and I can't figured out why. I've tried to implement some basics synchronization mechanism but nothing works.

Thanks a lot.

0

There are 0 answers