Java Reference
In-Depth Information
= secondsSince1900 - differenceBetweenEpochs ;
long msSince1970 = secondsSince1970 * 1000 ;
Date time = new Date ( msSince1970 );
System . out . println ( time );
}
}
UDPServer
Clients aren't the only programs that benefit from a reusable implementation. The
servers for these protocols are also very similar. They all wait for UDP datagrams on a
specified port and reply to each datagram with another datagram. The servers differ
only in the content of the datagram that they return. Example 12-9 is a simple iterative
UDPServer class that can be subclassed to provide specific servers for different protocols.
The UDPServer class has two fields, the int bufferSize and the DatagramSocket sock
et , the latter of which is protected so it can be used by subclasses. The constructor opens
a datagram socket on a specified local port to receive datagrams of no more than
bufferSize bytes.
UDPServer implements Runnable so that multiple instances can run in parallel. Its run()
method contains a loop that repeatedly receives an incoming datagram and responds
by passing it to the abstract respond() method. This method will be overridden by
particular subclasses in order to implement different kinds of servers.
Assuming this class may be used as part of other programs that do more than just run
one server, you need a way to shut it down. This is provided by the shutDown() method,
which sets a flag. The main loop checks this flag each pass to see if it should exit. Because
the receive() call can block indefinitely if there's no traffic, you also set a timeout on
the socket. This will wake it up once every 10 seconds to check for shutdown whether
there's traffic or not.
UDPServer is a very flexible class. Subclasses can send zero, one, or many datagrams in
response to each incoming datagram. If a lot of processing is required to respond to a
packet, the respond() method can spawn a thread to do it. However, UDP servers tend
not to have extended interactions with a client. Each incoming packet is treated inde‐
pendently of other packets, so the response can usually be handled directly in the
respond() method without spawning a thread.
Example 12-9. The UDPServer class
import java.io.* ;
import java.net.* ;
import java.util.logging.* ;
public abstract class UDPServer implements Runnable {
Search WWH ::




Custom Search