Java Reference
In-Depth Information
Notice that each of the six constructors takes in an array of bytes. When
receiving a packet, the array starts out empty and is filled with the incoming
datagram packet. When sending a packet, the array of bytes contains the data
of the packet to be sent.
The DatagramPacket class contains accessor and mutator methods for the
various attributes of the datagram packet:
public byte [] getData().
Returns the data buffer.
public void setData(byte [] buffer).
Sets the data of the packet.
public int getLength().
Returns the length of the data to be sent or
received.
public void setLength(int length).
Sets the length of the data to be sent
or received.
public SocketAddress getSocketAddress().
Returns the address of the
remote host where the message is being sent to or received from.
public void setSocketAddress(SocketAddress address).
Sets the address
of the remote host where the message is being sent to or received from.
Now, let's look at an example of how to use these classes to send and receive
datagram packets using UDP.
Receiving a Datagram Packet
To receive a datagram packet, the following steps are performed:
1.
Create an array of bytes large enough to hold the data of the incoming
packet.
2.
A DatagramPacket object is instantiated using the array of bytes.
3.
A DatagramSocket is instantiated, and it is specified which port (and
specific localhost address, if necessary) on the localhost the socket will
bind to.
4.
The receive() method of the DatagramSocket class is invoked, passing
in the DatagramPacket object. This causes the thread to block until a
datagram packet is received or a time out occurs.
After the receive() method returns, a new packet has just been delivered
successfully. (Note that if a time out occurs, the receive() method does not
return, but instead throws an exception.) The getData() method of the Data-
gramPacket class can be used to retrieve the array of bytes containing the data
of this packet.
The following PacketReceiver program demonstrates the steps involved in
receiving a datagram packet.