Java Reference
In-Depth Information
well as different hosts. In this case, setPort() could be used in conjunction with se
tAddress() to change destinations before sending the same datagram out again.
public void setAddress(SocketAddress remote)
The setSocketAddress() method changes the address and port a datagram packet is
sent to. You can use this when replying. For example, this code fragment receives a
datagram packet and responds to the same address with a packet containing the string
“Hello there”:
DatagramPacket input = new DatagramPacket ( new byte [ 8192 ], 8192 );
socket . receive ( input );
DatagramPacket output = new DatagramPacket (
"Hello there" . getBytes ( "UTF-8" ), 11 );
SocketAddress address = input . getSocketAddress ();
output . setAddress ( address );
socket . send ( output );
You could certainly write the same code using InetAddress objects and ports instead
of a SocketAddress . The code would be just a few lines longer.
public void setLength(int length)
The setLength() method changes the number of bytes of data in the internal buffer
that are considered to be part of the datagram's data as opposed to merely unfilled space.
This method is useful when receiving datagrams, as we'll explore later in this chapter.
When a datagram is received, its length is set to the length of the incoming data. This
means that if you try to receive another datagram into the same DatagramPacket , it's
limited to no more than the number of bytes in the first. That is, once you've received
a 10-byte datagram, all subsequent datagrams will be truncated to 10 bytes; once you've
received a 9-byte datagram, all subsequent datagrams will be truncated to 9 bytes; and
so on. This method lets you reset the length of the buffer so that subsequent datagrams
aren't truncated.
The DatagramSocket Class
To send or receive a DatagramPacket , you must open a datagram socket. In Java, a
datagram socket is created and accessed through the DatagramSocket class:
public class DatagramSocket extends Object
All datagram sockets bind to a local port, on which they listen for incoming data and
which they place in the header of outgoing datagrams. If you're writing a client, you
don't care what the local port is, so you call a constructor that lets the system assign an
unused port (an anonymous port). This port number is placed in any outgoing data‐
grams and will be used by the server to address any response datagrams. If you're writing
a server, clients need to know on which port the server is listening for incoming data‐
grams; therefore, when a server constructs a DatagramSocket , it specifies the local port
Search WWH ::




Custom Search