/**
 * A server listening on the port specified in the command line.
 * This server reads 10 numbers from the client and sends back the square roots
 * of those numbers. 
 */

import java.net.*;
import java.io.*;
import java.util.*;

public class  SqrtServer
{
	public static void main(String[] args) throws IOException {
		if (args.length != 1) {
			System.err.println("Usage: java EchoServer &lt;Port Number&gt;  ");
			System.exit(0);
		}

		ServerSocket sock = null;

		try {
			// establish the socket
			sock = new ServerSocket(Integer.parseInt(args[0]));

			/**
			 * listen for new connection requests.
			 * when a request arrives, service it
			 * and resume listening for more requests.
			 */
			while (true) {
				// now listen for connections
				Socket client = sock.accept();

				// service the connection
				ServiceConnection(client);
			}
		}
		catch (IOException ioe) {
			System.err.println(ioe);
		}
		finally {
			if (sock != null)
				sock.close();
		}
	}

	public static void ServiceConnection(Socket client)
	{
		BufferedReader networkBin = null;
		OutputStreamWriter networkPout = null;
		int count = 0;
		double number = -1;
		double sqrtnum = -1;
		ArrayList myarray1 = new ArrayList(10);
		ArrayList myarray2 = new ArrayList(10);

		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 the square root of what was read. 
			 * The loop terminates with ^D or after 10 numbers have been read
			 * from the  input stream.
			 */
			while (count < 10) {
				String line = networkBin.readLine();
				if (line == null) {
					break;
				}
				System.out.println("Received from client : "+line);
				try {
					number = Double.parseDouble(line);
				}
				catch (Exception e) {
					System.out.println(e);
					networkPout.write("Server error: "+e.toString());
				}

				sqrtnum = Math.sqrt(number);
				myarray1.add(count, number);
				myarray2.add(count, sqrtnum);

				networkPout.write("Server [ Recieved input number "+number+" ]\r\n");
				networkPout.flush();
				count = count + 1;
			}
			/**
			 * Write back to the client all 10 results (or as many as 
			 * they have sent if less than 10)
			 */
			for (int i=0;i<10;i++)
			{
				networkPout.write("Server [ The square root of "
				+ myarray1.get(i) +
				" is " + myarray2.get(i) + " ]\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);
			}
		} // end try
	} // end ServiceConnection
}

