简体   繁体   中英

Java packet sending with bytebuffer

I'm having some problem sending datagram packets in java. I have part of my code below.

Sender:

    String str = "abcdefghijk.txt"
    byte[] data = new byte[1000];
    ByteBuffer buf = ByteBuffer.wrap(data);
    buf.put(str.getBytes());
    //data = str.getBytes();     line 1

    //checksum
    crc.reset();
    crc.update(data, 8, data.length-8);
    checksum = crc.getValue();

    buf.rewind();
    buf.putLong(checksum);

    packet = new DatagramPacket(data, data.length, address);        

Receiver:

      packet.setLength(data.length);
      socket.receive(packet);
      data = packet.getData();   
      str = new String(data);  
      str = str.trim();

      buf.rewind();
      checksum = buf.getLong();
      crc.reset();
      crc.update(data, 8, packet.getLength()-8);

I will then do a check by using checksum==crc.getValue(). If i run the code as it is, my checksum is valid but the str received will be like this -> @#$%ijk.txt (garbage values infront). First 8 characters are gone in this case, which I think has something to do with the getLong().

However if i use line 1 in my code, the str received is correct (abcdefghijk.txt), but the checksum will be wrong.

Note that the code is not the entire thing but only the part that is affecting the output. Any help will be appreciated.

I believe your problem here is you consider that your packet will arrive in one chunk, but Streams have the property to cut the data into slices.

On the output, you have to encapsulate your data to know where you start and where you stop.

At the input, you have to rebuild your buffer chunk by chunk until you find that 'end tag'.

Are you using ObjectStreams ? If so, be aware they send and receive their own identifiers through the streams. It could explain the missing 8 bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM