/**
 * A separate thread that is created by the server. This thread is used
 * to interact with the client.
 *
 * @ author - Greg Gagne, January 2002.
 */
//The java.io classes allow input and output streams,etc, to be created
//to access and use input output devices, including sockets
//The java.net classes are required for socket communication
import java.io.*;
import java.net.*;

//Extend the Thread class with Connection
public class Connection extends Thread
{
	private Socket client;
	
	//Constructor, sets client = Socket c (passed in)
	public Connection(Socket c) {
		client = c;
	} 

	/**
	 * this method is invoked as a separate thread
	 */
	 
	//In a multithreaded class the run() method creates the thread logic 
	public void run() {
		
		//Create null BufferedReader to later check for exceptions
		BufferedReader networkBin = null;
		//Create null 	OutputStreamWriter to later check for exceptions
		OutputStreamWriter networkPout = null;
		
		try {
			/**
			 * get the input and output streams associated with the socket.
			 */
			networkBin = new BufferedReader(new InputStreamReader(client.getInputStream()));
			networkPout = new OutputStreamWriter(client.getOutputStream());

			/**
			 * the following successively reads from the input stream and returns
			 * what was read. The loop terminates when we read a period "."
			 * from the  input stream.
			 */
			boolean done = false;	
			while (!done) {
				//Inside the loop, each transaction is processed by the
				//processing rules or statements
				//readLine reads the message from the client connection
							
				String line = networkBin.readLine();
				//Tokenizer or other parsing can be used here to manipulate input
				//from socket
				
				if ( (line == null) || line.equals(".") ) {
					//stop the client connection if . is input					
					done = true;
					networkPout.write("BYE\r\n");
				}
				else 
					//Where the processing occurs
					//Account statements, Books, any classes can
					//be instantiated from here,.				
					System.out.println("Threaded Server Connection " + line);
					networkPout.write(">>"+line+"<<\r\n");

				networkPout.flush();
			}
		}
		catch (IOException ioe) {
			System.err.println(ioe);
		}
		finally {
			try {
				if (networkBin != null)
					networkBin.close();
				if (networkPout != null)
					networkPout.close();
				if (client != null)
					client.close();
			}
			catch (IOException ioee) {
				System.err.println(ioee);
			}
		}
	}

}