Question

I'm trying to understand the significance of the offset field of an OutputStream's write() function. It makes a lot of sense to me in the case of a file output, where seeking is a thing...but if I'm connected to a TCP stream like so:

Socket mSocket = null;
OutputStream mOutputStream = null;
byte[] msgBytes = {some message};
mSocket = new Socket();
mSocket.connect(new InetSocketAddress({arbitrary IP},{arbitrary port}));
mOutputStream = mSocket.getOutputStream();

and I send bytes like so:

// length is the length of msgBytes.
mOutputStream.write(msgBytes, 0, length);
//msgBytes2 is another message with length2
mOutputStream.write(msgBytes2, length, length2);

Does this have any different effect if I always set offset to 0 like so?

// length is the length of msgBytes.
mOutputStream.write(msgBytes, 0, length);
//msgBytes2 is another message with length2
mOutputStream.write(msgBytes2, 0, length2);

The codebase I'm working on sometimes sends 0, sometimes sends the length of the previous message. I know that if I manually send something large in that offset, I get an out of bounds error. Just trying to understand the effects of this...it doesn't make sense to me that any value of offset would be honored, since the message will immediately start streaming out the TCP port once the write call finishes, right?

Was it helpful?

Solution

The offset is the position in the byte[] pass to start copying data.

From the Javadoc for ObjectStream.write(byte[], int, int)

Writes len bytes from the specified byte array starting at offset off to this output stream. The general contract for write(b, off, len) is that some of the bytes in the array b are written to the output stream in order; element b[off] is the first byte written and b[off+len-1] is the last byte written by this operation.

It is nothing more complicated than that and it doesn't make sense to use a length from an unrelated byte[] as an offset.


//msgBytes2 is another message with length2
mOutputStream.write(msgBytes2, length, length2);

This caases length2 to start from length it is similar to

for(int i = length; i < length + length2; i++
    mOutputStream.write(msgBytes2[i]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top