The DatagramPacket class is a
wrapper for an array of bytes from which data will be sent or into which data
will be received. It also contains the address and port to which the packet
will be sent.
public DatagramPacket(byte[] data, int length)
public DatagramPacket(byte[] data, int length,
InetAddress host, int port)
You construct a DatagramPacket
object by passing an array of bytes and the number of those bytes to send to
the DatagramPacket() constructor like this:
String s = "My first UDP Packet"
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length);
Normally you'll also pass in the
host and port to which you want to send the packet:
try {
InetAddress metalab = new InetAddress("netparam.com");
int chargen = 19;
String s = "My second UDP Packet"
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, metalab, chargen);
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
The byte array that's passed to the
constructor is stored by reference, not by value. If you cahnge it's contents
elsewhere, the contents of the DatagramPacket change as well.
DatagramPackets themselves are not
immutable.
You can
change the data, the length of the data, the port, or the address at any time
with these four methods:
public void setAddress(InetAddress host)
public void setPort(int port)
public void setData(byte buffer[])
public void setLength(int length)
You can
retrieve these items with these four get methods:
public InetAddress getAddress()
public int getPort()
public byte[] getData()
public int getLength()
These methods are primarily useful
when you're receiving datagrams.