java: receiving UDP packet and how to save them

2019-08-28 01:50发布

问题:

I receive udp data in my array (byte[] data) from simulink udp block . the data is packed as int32 , so first I need to unpack that .

I don't know how can I save this data to be able to use that . these data are positions and I want to visualize them using OpenGL ES. I want to save the data into an array and be able to add the next packets to that array in next iteration, not rewrite the whole array (because of the loop )

the size of the data is 1200 * 96 for now . is array a good option ?

       int j = 0 ;
  float[] bin1 = new float[(data.length/2)];
  while (j < data.length ) {
    if ( data[2*j+2] >= 0  ) {

      String unhx =(binary(data[2*j+3])+binary(data[2*j+2])+binary(data[2*j+1])+binary(data[2*j]));
      float unbin = ((float)unbinary(unhx)/100);
      bin1[j/2] = unbin;
      print(bin1[1]);
    }

    else if  ( data[2*j+2] < 0 && data[2*j+3] < 0 ) {
      data[2*j] = (byte)(-data[2*j]);
      data[2*j+1] = (byte)(-data[2*j+1]);
      String unhx =(binary(data[2*j+1])+binary(data[2*j]));
      float unbin = ((-1)*(float)unbinary(unhx)/100);
      bin1[j/2] = unbin;
      print(bin1[1]);
      }
      j = j + 2;
  }

now the problem is that each time the new packet comes it rewrites the whole bin1 array , how could I add the new packets to the bin1 not rewrite the whole thing?

回答1:

One problem what i see here is in while loop you are using counter as variable int j=0 but no where you are incrementing your counter variable j that may be the problem.

j = 0 ;
while (j < data.length){
float[] array = new float[] {myData};
j++;
}


回答2:

Again Melisa, you have to declare your array(s) BEFORE you enter the while loop. So that they will remain in scope once you leave the loop. This means, you'll still be able to access the array after you leave the loop. :) Hope this helps.



回答3:

Reply to your edited question:

Melisa, you might want to consider using a List of floats rather than an array of floats. Otherwise, you might find yourself resizing and copying over the array to add on more data. A list/linked list theoretically has unlimited length (you really don't have to concern yourself with the length) and you can just keep adding on floats.

List



标签: java udp