Java Reference
In-Depth Information
Several factors are involved in choosing the optimal packet size. If the network is highly
unreliable, such as a packet radio network, smaller packets are preferable because they're
less likely to be corrupted in transit. On the other hand, very fast and reliable LANs
should use the largest packet size possible. Eight kilobytes—that is, 8,192 bytes—is a
good compromise for many types of networks.
It's customary to convert the data to a byte array and place it in data before creating the
DatagramPacket , but it's not absolutely necessary. Changing data after the datagram
has been constructed and before it has been sent changes the data in the datagram; the
data isn't copied into a private buffer. In some applications, you can take advantage of
this. For example, you could store data that changes over time in data and send out the
current datagram (with the most recent data) every minute. However, it's more impor‐
tant to make sure that the data doesn't change when you don't want it to. This is especially
true if your program is multithreaded, and different threads may write into the data
buffer. If this is the case, copy the data into a temporary buffer before you construct the
DatagramPacket .
For instance, this code fragment creates a new DatagramPacket filled with the data “This
is a test” in UTF-8. The packet is directed at port 7 (the echo port) of www.ibiblio.org :
String s = "This is a test" ;
byte [] data = s . getBytes ( "UTF-8" );
try {
InetAddress ia = InetAddress . getByName ( "www.ibiblio.org" );
int port = 7 ;
DatagramPacket dp = new DatagramPacket ( data , data . length , ia , port );
// send the packet...
} catch ( IOException ex )
}
Most of the time, the hardest part of creating a new DatagramPacket is translating the
data into a byte array. Because this code fragment wants to send a string, it uses the
getBytes() method of java.lang.String . The java.io.ByteArrayOutputStream
class can also be very useful for preparing data for inclusion in datagrams.
The get Methods
DatagramPacket has six methods that retrieve different parts of a datagram: the actual
data plus several fields from its header. These methods are mostly used for datagrams
received from the network.
public InetAddress getAddress()
The getAddress() method returns an InetAddress object containing the address of
the remote host. If the datagram was received from the Internet, the address returned
 
Search WWH ::




Custom Search