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

/**
 * The threaded version of a knock-knock joke server. 
 * 
 * @author Matt Boutell, based on the Java Tutorial. 
 * 		Created Oct 15, 2006.
 */
public class KnockKnockServer {

	/**
	 * Execution starts here.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		ServerSocket server = null;
		Socket client = null;
		boolean listening = true;
		try {
			server = new ServerSocket(4321); // port
		} catch (IOException e) {
			System.err.println("Could not listen on port 4321.");
			System.exit(1);
		}

		try {
			// Loop, waiting for clients to connect.
			while (listening) {
				// Details of connection encapsulated in the accept method.
				client = server.accept();
				
				// Spawn a thread to deal with a single client.
				KnockKnockServerThread kkst = new KnockKnockServerThread(client);

				// Don't forget to kick it off; start() calls run().
				kkst.start();
				System.out.println("KnockKnockServer connected to "
						+ client.getInetAddress());
			}
			server.close();
			client.close();
		} catch (IOException e) {
			System.err.println("Could not accept connection.");
			System.exit(1);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}