i've got two threads which continuously manage I/O operations on the streams of a BluetoothSocket.
For the input, no problem.. the InputStream.read() method is blocking and everything's fine.
For the output.. here it comes the problem.
public void write(final byte[] buffer) {
synchronized (this) {
try {
this.mOutStream.write(buffer);
this.mHandler.sendEmptyMessage(Constants.MESSAGE_SENT);
} catch (IOException e) {
Log.e(LOGTAG, "Exception during write", e);
}
}
}
I use the code above for writing messages on the output stream. It's synchronized on the instance of the thread so that nobody else will be able to write on the buffer competitively.
The problem is the following: if I try to write two messages, the one immediately after the other, the first one seems to be skipped by the receiving device.
Reading what OutputStream.write(byte[]) does, I understand what's the main reason: it's like calling OutputStream(byte[], 0, length), so the '0' offset will overwrite the previous message.
But I cannot set timers or timeouts every time I need to write two messages sequentially, just to be sure that in the meantime the first message has already been read by the recipient.
I want something more, something like this:
int offset = 0;
this.mOutputStream.setOnStreamEmptiedCallback(new OnStreamEmptiedCallback() {
public void onStreamEmptied() {
this.offset = 0;
}
});
public void write(byte[] buffer) {
this.mOutputStream.write(buffer, 0, buffer.length);
this.offset += buffer.length;
}
I know that the setOnStreamEmptiedCallback
doesn't exist, but.. Is there a way to do something similar? Something to be sure that I will never overwrite the stream content?
Thanks everybody..