Poula Adel
Poula Adel

Reputation: 639

Java UDP datagram packet - slicing data to suit buffer size

in Java, UDP datagram packets uses a fixed size of byte array to send and receive streams through the network.

  1. if the data I want to send is bigger than the buffer how to slice the data to suit the datagram packet ?
  2. if data is sliced at the client side to suitable datagrams, how to know the number of packets I should receive ?
  3. if I used String.getBytes() at the client side to send all data in one buffer, then at the server how know the exact length of packet or data I need to receive as all data I should receive ?

plus: I know that UDP packet should not be too long (i.e. not exceeding 548 byte), that means slicing the data at client is more efficient.

Upvotes: 1

Views: 1992

Answers (1)

Craig S. Anderson
Craig S. Anderson

Reputation: 7374

Here is what I would do:

  1. Choose a maximum datagram size N you will send - 548 for example. You could try larger values up to 65535.
  2. Split the data into chunks of size N - 6.
  3. In each chunk, use 2 bytes for the datagram number and 2 bytes for the datagram length. Use the 2 remaining bytes to send the total number of datagrams. Yes this "wastes" 2 bytes in most datagrams but it makes the code simpler.

When each datagram is received, use the first 6 bytes to reassemble the datagrams into the complete data.

Upvotes: 2

Related Questions