سؤال

I have packets that are sent over sockets which are preceded by length headers. So every transmission comes with 4 bytes of length information followed by the packet. Therefore, I must limit my read() to never exceed the length, so that I don't accidentally read the next packet in line.

InputStream in is the input stream, ByteArrayOutputStream byteStream is the stream I write incoming packets into and int len is the length of an incoming transmission.

Here is what I came up with:

for (int i = 0; i < len; i++) {
    byteStream.write(in.read());
}

This is absolutely horrific; reading bytes one by one. I was hoping to see if there is a better way of doing this using buffers (kind of similar to the canonical way of copying streams).

هل كانت مفيدة؟

المحلول

Wrap the input stream in a DataInputStream and then use the readInt() and readFully() methods to get the size and bytes of data out.

int len = dis.readInt();
// assuming relatively small byte arrays, use smarter logic for huge streams....
byte[] buffer = new byte[len];
dis.readFully(buffer);
byteStream.write(buffer);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top