Java Reference
In-Depth Information
InetAddress host = InetAddress . getByName ( "time.nist.gov" );
DatagramPacket request = new DatagramPacket ( new byte [ 1 ], 1 , host , 13 );
The packet that receives the server's response just contains an empty byte array. This
needs to be large enough to hold the entire response. If it's too small, it will be silently
truncated—1k should be enough space:
byte [] data = new byte [ 1024 ];
DatagramPacket response = new DatagramPacket ( data , data . length );
Now you're ready. First send the packet over the socket and then receive the response:
socket . send ( request );
socket . receive ( response );
Finally, extract the bytes from the response and convert them to a string you can show
to the end user:
String daytime = new String ( response . getData (), 0 , response . getLength (),
"US-ASCII" );
System . out . println ( daytime );
The constructor and send() and receive() methods can each throw an IOException ,
so you'll usually wrap all this in a try block. In Java 7, DatagramSocket implements
Autocloseable so you can use try-with-resources:
try ( DatagramSocket socket = new DatagramSocket ( 0 )) {
// connect to the server...
} catch ( IOException ex ) {
System . err . println ( "Could not connect to time.nist.gov" );
}
In Java 6 and earlier, you'll want to explicitly close the socket in a finally block to
release resources the socket holds:
DatagramSocket socket = null ;
try {
socket = new DatagramSocket ( 0 );
// connect to the server...
} catch ( IOException ex ) {
System . err . println ( ex );
} finally {
if ( socket != null ) {
try {
socket . close ();
} catch ( IOException ex ) {
// ignore
}
}
}
Example 12-1 puts this all together.
Search WWH ::




Custom Search