I have a network Socket read that works fine in below case:
Sender sends bytes of size_t
. Receiver knows value of size_t, and uses
do {
long tse = System.currentTimeMillis();
bytesRead = inputStream.read(buffer,current,buffer.length-current));
Log.e("time-spent",String.valueOf(System.currentTimeMillis()-tse));
if(bytesRead >= 0) {
current += bytesRead
}
} while(bytesRead > 0);
where buffer
is of size size_t
. While loop is used because, read doesnot grab entire data in a single attempt unlike write does!
Now if the sender each time sends variable amount of data,which is not known to receiver, the above code doesnot coming out of wuile loop. Also if i simply give inputStream.read(buffer,current,1024-current));
it seems read only upto 1024 bytes and comes out of loop.
I want to receive variable amount of data ranging from 1kb to 500kb
. How can i using ordinary char[] arrays and TCP sockets(UDP as well) but not using NIO ByteBuffers!
I would design an application packet structure to include the length field as the first byte(s) to be received. This will allow the receiver to understand how many bytes are coming in and plan accordingly.
Simply create a structure that looks like this:
length
: the length of the message being sent.
payload
: the data being sent that is of size length
You can structure payload
to also be a little more descriptive than just byte[]
; make an class that is Serializable
that represents your message.
Once you have a well defined application packet, create a parser that understands the structure of the packet for the receiver. This parser will then receive the first byte or bytes and know that those bytes represent the length
of the payload
. It will then read the payload
accordingly. If the payload
doesn't match the length
, the packet is invalid.
If you're forced to simply use char[]
, you can do something like this:
char[] message = { 0x05, 'h', 'e', 'l', 'l', 'o' }; // 0x05 is the length field
Notice how length
is not including itself in the number of bytes.
This design is something that can be utilized on any platform for communication: from RF transceivers in embedded systems to TCP communication on Android.