Need help receiving ByteArray data
I am trying to receive byte array data from a machine. It sends out 3 different types of data structure each with different number of fields which consist of mostly int and a few floats, and byte sizes, the first being 320 bytes, 420 for the second type and 560 for the third. When the sending program is launched, it fires all 3 types of data simultaneouly with an interval of 1 sec. Example:
Sending order: Pack1 - 320 bytes 1 sec later Pack2 - 420 bytes 1 sec later Pack3 - 560 bytes 1 sec later Pack1 - 320 bytes ... .. .
How do I check the incoming byte size before passing it to:
byte[] handsize = new byte[bytesize];
as the data I receive are all out of order, for instance using the following the read all int:
System.out.println("Reading data in int format:" + " " + datainput.readInt());
I get many different sets of values whenever I run my prog although with some valid field data but they are all over the place.
I am not too sure how exactly should I do it but I tried the following and apparently my data fields are not receiving in correct sequence:
BufferedInputStream bais = new
BufferedInputStream(requestSocket.getInputStream());
DataInputStream datainput = new DataInputStream(bais);
byte[] handsize = new byte[560];
datainput.readFully(handsize);
int n = 0;
int intByte[] = new int[140];
for (int i = 0; i < 140 ; i++) {
System.out.println("Reading data in int format:" + " " + datainput.readInt());
intByte[n] = datainput.readInt();
n = n + 1;
System.out.println("The value in array is:" + intByte[0]);
System.out.println("The value in array is:" + intByte[1]);
System.out.println("The value in array is:" + intByte[2]);
System.out.println("The value in array is:" + intByte[3]);
Also from the above co开发者_JAVA百科de, the order of the values printed out with
System.out.println("Reading data in int format:" + " " + datainput.readInt());
and
System.out.println("The value in array is:" + intByte[0]);
System.out.println("The value in array is:" + intByte[1]);
are different.
Any help will be appreciated. Thanks
you can't. you need to explicitly send the data length (or data type which you will derive the length from) before the data, or have another method of looking at the data and figuring out it's lengh (self describing, like a null terminated string).
edit: Another way to figure out the length is to put a single message within a single TCP session. not recommended because it's too much overhead but it will work.
You call datainput.readInt()
twice in every iteration of the loop. You probably wanted to read only one int in every iteration.
精彩评论