Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transferring large amounts of data over bluetooth on Android Gingerbread

I'm trying to transfer about a megabyte of arbitrary data at a time from one android phone to another. Currently, I write the size, a command code and the data to a DataOutputStream around a BufferedOutputStream, around the OutputStream returned from bluetoothSocketInstance.getOutputStream().

The receiving phone reads the size and command code and then reads from the input stream until it has gotten all the data it is expecting. This works for short strings, but for larger files not all the data is transferred. Running the app in the debugger shows that the write returns without any exceptions and the read reads a fraction of the bytes expected and then blocks indefinitely. It also does not throw any exceptions.

Is there a buffer somewhere that is filling up? Is there something else I need to do to ensure that all the data gets transferred?

My code for the sender and receiver are below:

Sender:

  try {

            DataOutputStream d = new DataOutputStream(new BufferedOutputStream(mmOutStream,buffer.length+8));
            //int b= buffer.length;
            d.writeInt(buffer.length);
            d.writeInt(command);

            d.write(buffer);
            d.flush();

        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

Receiver:

 try {

                // Read from the InputStream
                int messageSize= inStream.readInt();
                int messageCode = inStream.readInt();
                bytes=0;
                buffer =new byte[messageSize];
                while(bytes < messageSize)
                {
                    bytes += inStream.read(buffer,bytes,messageSize - bytes);

                }
                    message = bytes;
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
like image 600
ethan Avatar asked Oct 23 '22 19:10

ethan


1 Answers

After some more testing on my end, I changed my sending code to look like this:

for(int i=0; i<buffer.length;i+=BIG_NUM)
            {
                int b = ((i+BIG_NUM) < buffer.length) ? BIG_NUM: buffer.length - i;
                d.write(buffer,i,b);
                d.flush();
            }

The files now get sent. Does anyone have an idea why? Does the call to flush() block until the data has actually been transferred? Is there any documentation about the size of the send and receive buffers that would help me to decide how large I can safely make BIG_NUM?

like image 189
ethan Avatar answered Nov 04 '22 21:11

ethan