Java Reference
In-Depth Information
DatagramPacket request = new DatagramPacket ( new byte [ 1024 ], 0 , 1024 );
Then receive it:
socket . receive ( request );
This call blocks indefinitely until a UDP packet arrives on port 13. When it does, Java
fills the byte array with data and the receive() method returns.
Next, create a response packet. This has four parts: the raw data to send, the number of
bytes of the raw data to send, the host to send to, and the port on that host to address.
In this example, the raw data comes from a String form of the current time, and the
host and the port are simply the host and port of the incoming packet:
String daytime = new Date (). toString () + "\r\n" ;
byte [] data = daytime . getBytes ( "US-ASCII" );
InetAddress host = request . getAddress ();
int port = request . getPort ();
DatagramPacket response = new DatagramPacket ( data , data . length , host , port );
Finally, send the response back over the same socket that received it:
socket . send ( response );
Example 12-2 wraps this sequence up in a while loop, complete with logging and ex‐
ception handling, so that it can process many incoming requests.
Example 12-2. A daytime protocol server
import java.net.* ;
import java.util.Date ;
import java.util.logging.* ;
import java.io.* ;
public class DaytimeUDPServer {
private final static int PORT = 13 ;
private final static Logger audit = Logger . getLogger ( "requests" );
private final static Logger errors = Logger . getLogger ( "errors" );
public static void main ( String [] args ) {
try ( DatagramSocket socket = new DatagramSocket ( PORT )) {
while ( true ) {
try {
DatagramPacket request = new DatagramPacket ( new byte [ 1024 ], 1024 );
socket . receive ( request );
String daytime = new Date (). toString ();
byte [] data = daytime . getBytes ( "US-ASCII" );
DatagramPacket response = new DatagramPacket ( data , data . length ,
request . getAddress (), request . getPort ());
socket . send ( response );
audit . info ( daytime + " " + request . getAddress ());
} catch ( IOException | RuntimeException ex ) {
Search WWH ::




Custom Search