I hava a question. I want to send an array of bytes through a socket but I don't want to send the length of it. Cand I read it from a server side?
I've tried something like this:
dos = new DataOutputStream(socket.getOutputStream);
dos.write(myByteArray);
and on the server side
byte data = new data[100];
dis.read(data);
but in this way, I read 100 bytes or another no of bytes. Can I read exacty the no. of bytes I send? Thanks
Can I read exacty the no. of bytes I send?
If you are sending arbitrary bytes without any form of encoding, then either you need to send a length (first) or you need to close the socket stream after writing the last byte.
If you can encode the bytes1, or if you are guaranteed that certain bytes never appear, then the client can send a special "end-of-byte-array" marker after the last byte of the array.
AFAIK, there is no other reliable solution2.
1 - For instance, the encoding could be as simple as reserving one of the 256 possible byte values as an "escape" byte, and using two escapes to signify that value when you want to send it as data.
2 - Consider this "solution". After writing the bytes, the client waits at least N seconds before sending any more data. If the server doesn't see any bytes for N seconds, it interprets that as meaning that the further data is not part of the first byte array. The reason this is flaky is that if there is congestion or a temporary network outage, and the flow of data is delayed for > N seconds, it will look to the server like the client has finished, when it hasn't.