1

I have wrote a generic program that can accept data from DataInputStream. But recently I was trying to receive data from UDP using DatagramSocket. I have searched a lot, but I could nor fina a way to manipulate the incoming data from DatagramSocket to DataInputStream. Logically, since both are incoming data, there should be a way to integrate these two objects right? Am I wrong?

After getting answered from EJP I am right now using like this am i right?

byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength()));
While(true){
    dsocket.receive(packet);
    dis = new DataInputStream(new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength()));
    reader = new MAVLinkReader(dis,MAVLinkMessage.MAVPROT_PACKET_START_V10);
    mesg = reader.getNextMessage();
    while (mesg != null) {...do stuff...}
}

Now what i feel is that since the reader is initialized to new dis each time the previously remaining bytes in dis becomes vanished.

user207421
  • 305,947
  • 44
  • 307
  • 483
Anand
  • 693
  • 1
  • 8
  • 26
  • 1
    Of course they've vanished. What did you expect? You need to read the DataInputStream to its end before reading another packet. Aren't you doing that? – user207421 Apr 05 '16 at 16:57
  • No, in my case it is a stream of bits that comes in the form of packets. If a new packet is started in a datastream it is getting erased in the next run. So some how I should readback remaining part of the datastram and merge it with the beginning part of the new data stream so that my packet is re-obtained. – Anand Apr 05 '16 at 17:07
  • None of that is evident in the code you posted. You will lose data in any input stream if you don't read it to end of stream. This is not the fault of the `DataInputStream` or the `ByteArrayInputStream`. It is a bug in your code, and furthermore it is a bug in code you haven't posted. – user207421 Apr 06 '16 at 01:51

1 Answers1

3

Easy.

DataInputStream din = new DataInputStream(new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength());

where packet is a DatagramPacket.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thank you! This is what am exactly looking for. But whenever a new packet arrives should I call the above command? – Anand Mar 18 '16 at 09:38
  • I have used the above command, but i create new din for every time a new packet is received. This makes me to loose some of the bits of the packets. – Anand Apr 05 '16 at 12:53
  • 1
    @Anand Only if you didn't read the prior one to end of stream. – user207421 Apr 05 '16 at 17:28