/*
 *  Kholoud Khateeb, Craig Ward
 *  CMSI 698, Internet Technologies
 *  Homework Assignment 2, February 27, 2003
 */

import java.net.Socket;
import java.net.ServerSocket;
import java.io.IOException;

/**
 * An abstract class to simplify creating threaded network servers processes.
 *
 * A server class extends this class and provides concrete implementations of
 * the two methods spawn() and run().
 *
 * spawn(Socket socket): This methods allows the implementing class receive the
 * Socket object with the client request and to do some initalization for that
 * request.
 *
 * run(): This is the required method for the Runnable interface.
 */
public abstract class GenericThreadedServer
    implements Runnable
{
    private ServerSocket listener;

    /* Provide a placeholder for a default constructor */

    public GenericThreadedServer() {  }

    /**
     * Constructor for the instance of the server object that will do the
     * actual listen and accept work.
     */
    public GenericThreadedServer(int listenOn) throws IOException
    {
	this.listener = new ServerSocket(listenOn);
    }

    /**
     * Loop forever waiting for requests for whatever service the server
     * provides.
     */
    public void listen() throws IOException
    {
	try {
	    while (true) {
		spawn(listener.accept());
	    }
	} finally {
	    listener.close();
	}
    }

    /**
     * This method is called from the listen() method. It is intended to
     * provide the server with socket that the service will be delivered on and
     * an opportunity to perform any additional setup before creating a new
     * service thread.
     */
    public abstract void spawn(Socket socket);

    /**
     * Required method for the Runnable interface. This should be where most of
     * the actual service work is provided.
     */
    public abstract void run();

} // GenericThreadedServer
