receive DatagramPacket

In DatagramPacket class all constructors require an int parameter as "length". Why do I need to set the length of a DatagramPacket when I try to receive it, since I do not necessarily know how long the packet is? And which number should I set it to?

edit: Let me change my question to this:

if DatagramSocket.receive method has signature

public DatagramPacket receive() {};

instead of

public void receive(Datagrampacket p) {};

wouldn't it make more sense? since like said, the receiver usually does not know what the packet looks like.

Since the delivery service analogy is often applied to UDP, let's say:

DatagramSocket is like a mailbox. DatagramPacket is like the parcel envelope. DatagramPacket.data is the content inside envelope. For delivery service the receiver provides mailbox but not the envelope.

Upvotes: 1

Views: 804

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500485

Well, you're asking it to write into a byte array which you're also providing. So make sure your byte array is as large as the largest packet you would expect to handle, and pass in the length of the array for the length parameter.

EDIT: For the edited question, that API would mean the receiving code had to create a new buffer each time. With the existing API, the same byte array can be used for multiple calls, because the caller gets to decide when they've finished using it.

Now admittedly it would make sense to have an overload like this:

public DatagramPacket(byte[] buffer)
{
    this(buffer, buffer.length);
}

... but that's a different matter.

Upvotes: 1

Related Questions