/**
 * An echo server listening on port 6500. This server reads from the client
 * and echoes back the result. When the client enters the character '.' - the
 * server closes the connection.
 *
 * @ author - Greg Gagne, January 2002.
 *Modified by CIS135 class at SCCC
 */


//Contains classes needed for socket processing
import java.net.*;
import java.io.*;

//Class name is EchoServer
public class  EchoServer 
{
	//Main Method class starts here
	public static void main(String[] args) throws IOException {
		
		ServerSocket sock = null; //Declare null socket for later exception checking

		try {
			// establish the socket on port xxxx
			sock = new ServerSocket(6500);

			/**
			 * listen for new connection requests.
			 * when a request arrives, pass the socket to
			 * a separate thread and resume listening for
			 * more requests. 
			 * creating a separate thread for each new request
			 * is known as the "thread-per-message" approach.
			 */
			while (true) {
				// now listen for connections from clients
				Socket client = sock.accept();	

				// service the connection in a separate thread
				// Each connection will be spawned as a thread in 
				// the Connection class. Instantiating a Connection object
				// using the client socket as input. The Connection c becomes
				// a runnable thread.
				Connection c = new Connection(client);
				c.start(); //Connection c is runnable, so we start it as a thread
			}
		}
		
		//Catch socket IO exceptions
		catch (IOException ioe) {
			System.err.println(ioe);
		}
		finally {
			if (sock != null)
				sock.close();
		}
	}
}