Java Reference
In-Depth Information
The Constructors
DatagramPacket
uses different constructors depending on whether the packet will be
used to send data or to receive data. This is a little unusual. Normally, constructors are
overloaded to let you provide different kinds of information when you create an object,
not to create objects of the same class that will be used in different contexts. In this case,
all six constructors take as arguments a
byte
array that holds the datagram's data and
the number of bytes in that array to use for the datagram's data. When you want to
receive a datagram, these are the only arguments you provide. When the socket receives
a datagram from the network, it stores the datagram's data in the
DatagramPacket
object's buffer array, up to the length you specified.
The second set of
DatagramPacket
constructors is used to create datagrams you will
send over the network. Like the first, these constructors require a buffer array and a
length, but they also require an address and port to which the packet will be sent. In this
case, you pass to the constructor a
byte
array containing the data you want to send and
the destination address and port to which the packet is to be sent. The
DatagramSock
et
reads the destination address and port from the packet; the address and port aren't
stored within the socket, as they are in TCP.
Constructors for receiving datagrams
These two constructors create new
DatagramPacket
objects for receiving data from the
network:
public
DatagramPacket
(
byte
[]
buffer
,
int
length
)
public
DatagramPacket
(
byte
[]
buffer
,
int
offset
,
int
length
)
If the first constructor is used, when a socket receives a datagram, it stores the datagram's
data part in
buffer
beginning at
buffer[0]
and continuing until the packet is com‐
pletely stored or until
length
bytes have been written into the
buffer
. For example, this
code fragment creates a new
DatagramPacket
for receiving a datagram of up to 8,192
bytes:
byte
[]
buffer
=
new
byte
[
8192
];
DatagramPacket
dp
=
new
DatagramPacket
(
buffer
,
buffer
.
length
);
If the second constructor is used, storage begins at
buffer[offset]
instead. Otherwise,
these two constructors are identical.
length
must be less than or equal to
buffer.length
- offset
. If you try to construct a
DatagramPacket
with a length that will overflow the
buffer
, the constructor throws an
IllegalArgumentException
. This is a
RuntimeEx
ception
, so your code is not required to catch it. It is OK to construct a
DatagramPack
et
with a length less than
buffer.length - offset
. In this case, at most the first
length
bytes of
buffer
will be filled when the datagram is received.
The constructor doesn't care how large the buffer is and would happily let you create a
DatagramPacket
with megabytes of data. However, the underlying native network soft‐