/*
 * Created on Jan 19, 2005
 *
 */
package thegroup.projectcddb.server;

import java.net.*;
import java.io.*;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;

/**
 * a freeDB server
 * @author Alan Savage
 * @version 1.0
 */
public final class MultiServer {
	/**
	 * server listens on this port by default
	 */
	private static final int DEFAULT_PORT = 7777; 
        public static final Logger log = Logger.getLogger("thegroup.projectcddb.server.MultiServer");
        static FileHandler handler = null;
        static {
                try {
                        handler = new FileHandler("serverLog.txt", true);
                } catch (Exception e) {
                        System.err.println("Unable to create serverLog.txt");
                        e.printStackTrace();
                }
        }
        

	/**
	 * creates a MultiServer
	 * @param args command line arguments
	 */
	public static void main(String[] args) {
		new MultiServer(DEFAULT_PORT);		
	}
	
	/**
	 * creates a MultiServer that listens on DEFAULT_PORT
	 */
	MultiServer() {
		this(DEFAULT_PORT);
	}
	
	/**
	 * creates a MultiServer that listens on specified port
	 * @param port server listens on this port
	 */
	MultiServer(int port) {
                handler.setLevel(Level.ALL);
                handler.setFormatter(new SimpleFormatter());
                log.addHandler(handler);
                log.setLevel(Level.ALL);
                log.setUseParentHandlers(false);
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);
		} catch(IOException e) {
			log.severe("Unable to open port: " + port);
		}
		
		try {
			while(true) {
				new MultiClientThread(serverSocket.accept(), "ClientThread").start();
                        }
		} catch(IOException e) {
			log.severe("Unable to accept connection on port " + port);
		}
		
		try {
			serverSocket.close();
		} catch (IOException e) {
			log.warning("Unable to close port " + port);
		}
		
		System.out.println("Exiting");
		System.exit(0);
	}
}
