// The Threaded DateServer - The server application that passes control to the Handle Connection
// by Derek Molloy

import java.net.*;
import java.io.*;

public class ThreadedDateServer 
{
    public static void main(String args[]) 
    {
        ServerSocket serverSocket = null;
        try 
        {
            serverSocket = new ServerSocket(5050);
            System.out.println("Server has started listening on port 5050");
        } 
        catch (IOException e) 
        {
            System.out.println("Error: Cannot listen on port 5050: " + e);
            System.exit(1);
        }
        while (true) // infinite loop - loops once for each client
        {
            Socket clientSocket = null;
            try 
            {
                clientSocket = serverSocket.accept(); //waits here (forever) until a client connects
                System.out.println("Server has just accepted socket connection from a client");
            } 
            catch (IOException e) 
            {
                System.out.println("Accept failed: 5050 " + e);
                break;
            }	

	    // Create the Handle Connection object - our new thread object - only create it
            ThreadedHandleConnection con = new ThreadedHandleConnection(clientSocket);

            if (con == null) //If it failed send and error message
            {
                try 
                {
                    ObjectOutputStream os = new ObjectOutputStream(clientSocket.getOutputStream());
                    os.writeObject("error: Cannot open socket thread");
                    os.flush();
                    os.close();
                } 
                catch (Exception ex)  //failed to even send an error message
                {
                    System.out.println("Cannot send error back to client:  5050 " + ex);
                }
            }
            else { con.start(); } // otherwise we have not failed to create the HandleConnection object
				  // start this thread now
        }
        try  // do not get here at the moment 
        {
            System.out.println("Closing server socket.");
            serverSocket.close();
        } 
        catch (IOException e) 
        {
            System.err.println("Could not close server socket. " + e.getMessage());
        }
    }
}
