==> DateServer.java <==
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();
}
}
}
==> Registry.java <==
/**
* 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 point is that each time the server requests an instance of
* a Registry, it gets the same single instance. So that instance's
* field for keeping track of the connection count keeps getting incremented.
* The synchronization step is from Metsker's Java Workbook book.
*
Singleton Design Pattern example for COM1204 Summer 2003.
*
* @author Bob Futrelle
* @version 0.1, 5 July 2003
*
*/
public class Registry {
private static Registry registry = null; // (the default in any case)
private static final Object classlock = Registry.class;
private int connectionCount;
private Registry(){};
public void addToCount() {
connectionCount++;
}
public void report() {
System.out.println("Count now " + connectionCount);
}
public static Registry getRegistry() {
synchronized(classlock)
{
if (registry == null)
{
registry = new Registry();
}
return registry;
}
} // getRegistry
} // class Registry