import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; /** * This obeys the Singleton design pattern. * Only one instance of Registry can be generated. * It is used by DateServer to keep track of the number of connections made. * The synchronization step is from Metsker's Java Workbook book. * Most of the code is taken from Java in a Nutshell, 4th ed., pg. 187. * Run the DateServer on Denali and then * telnet to it via the command below * telnet denali.ccs.neu.edu 8379 * The server will then print info to stdout for each telnet connection made. * You might want to put in your own port number and recompile this. *
Singleton Design Pattern example for COM1204 Summer 2003. * * @author Bob Futrelle * @version 0.1, 5 July 2003 * */ public class DateServer { public static void main(String[] args) throws java.io.IOException { // Get a CharsetEncoder for encoding the text we send to the client CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); // Create a new ServerSocketChannel, and bind it to port 8379. // Note that we have to do this using the underlying ServerSocket. ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new java.net.InetSocketAddress(8379)); for(;;) { // This server runs forever // Wait for a client to connect. SocketChannel client = server.accept(); System.out.println("Got a connection"); // This returns a singleton, the single instance of Registry Registry registry = Registry.getRegistry(); registry.addToCount(); registry.report(); // Get the current date and time as a string String response = new java.util.Date().toString() + "\r\n"; // Wrap, encode, and send the string to the client client.write(encoder.encode(CharBuffer.wrap(response))); // Disconnect from the client client.close(); } } }