Reputation: 5409
If I had a byte stream which is encoded with the following format:
0x20 Length D_1 D_2 ... D_n CS
0x20...marks the beginning of a data frame
Length...number of bytes following
D_1-D_n...data bytes (interpreted as signed ints)
CS...One Byte Checksum
Example:
0x20 0x05 0x01 0x02 0xD1 0xA1 0xAF
0x20 0x05 0x12 0x03 0x02 0x3A 0xF2
...
...
How would I decode this byte stream from an InputStream in a way which is common and efficient? My idea is to use a BufferedInputStream and the following procedure (in pseudo code):
BufferedInputStream bufIS = new BufferedInputStream(mInStream);
while (true ) {
byte startFrame = bufIS.read();
if(startFrame == 0x20) { //first byte must mark the beginning of a data frame
int length = bufIS.read();
byte dataframe[] = new bye[length];
for (int i = 0; i<length i++) { //read data bytes
dateframe[i] = bufIS.read();
}
if(verifyChecksum(bufIS.read()) postEvent(dataframe);
}
}
Is this an appropriate way for receiving the data frames from the InputStream? I cant't think of a better solution for this. Also there's an alternative read(byte[] b, int off, int len)
method which reads chunks of bytes from the stream but it's not guaranteed that len
number of bytes are read, so i think this is not helpful in my case.
Upvotes: 0
Views: 584
Reputation: 19225
Id use an ObjectInputStream with custom deserialization.
So you'd write a class that has a List of ints and implements readObject such that when given an inputstream it reads the constant (and discards it), then the length, then n ints, then the checksum, and optionally validates it.
This keeps all the code in one place, and allows you to just read fully formed objects from your data stream.
Upvotes: 1
Reputation: 929
I'd did work on binary serialization at some stage and we did use BufferedInputStream with the read() method. Even more since we were using a network stream end the 'len' is almost always unrespected.
What we did instead was writing our own helper method the took a length and the buffer as parameters then return those byte for decoding use that we needed. We used that only when we are certain that we will get the full length of byte in our stream (well as long as it's a valid stream that we read)
Upvotes: 0