package chris.talker;

import java.lang.*;
import java.net.*;
import java.io.*;

public class Server extends java.lang.Object implements Runnable
{
    public Server(int iPort, String strClass)
    {
        this.iPort = iPort;
        this.strClass = strClass;
        
        start();
    }
    
    public void start()
    {
        if (tListener == null)
        {
            tListener = new Thread(this);
            tListener.start();
        }
    }
    
    public void run()
    {
        ServerSocket server = null;
        Socket sockConnection = null;
        Handler handler = null;

        try
        {
            server = new ServerSocket(iPort);
        }
        catch (IOException e)
        {
            System.err.println(e.toString() + ".  Shutting down Server "+server);
            bListening = false;
        }
            
        while (bListening)
        {
            // get a connection
            try
            {
                sockConnection = server.accept();
            }
            catch (IOException e)
            {
                System.err.println(e.toString() + ".  Shutting down Server "+server);
                sockConnection = null;
                bListening = false;
            }
            
            // create a handler
            if (sockConnection != null)
            {
                try
                {
                    handler = (Handler)Class.forName(strClass).newInstance();
                }
                catch (ClassNotFoundException e)
                {
                    System.err.println(e.toString()+".  Shutting down Server "+this);
                    bListening = false;
                }
                catch (InstantiationException e)
                {
                    System.err.println(e.toString()+".  Shutting down Server "+this);
                    bListening = false;
                }
                catch (IllegalAccessException e)
                {
                    System.err.println(e.toString()+".  Shutting down Server "+this);
                    bListening = false;
                }
            
                // pass the connection to the handler
                handler.setConnection(sockConnection);
            
                // start the handler
                handler.start();
            
                // clear the reference to the connection and handler
                // and wait for the next connection
                sockConnection = null;
                handler = null;
            }
        }
    }
    
    public boolean isListening()
    {
        return bListening;
    }
    
    public void setListening(boolean bListening)
    {
        this.bListening = bListening;
    }
    
    Thread tListener = null;
    int iPort;
    String strClass;
    boolean bListening = true;
}