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


        // Contact the echo server running on hostname.
class TCPEchoClient {
        // Contact the server at the appropriate port and set
        // the socket attribute for the run() method to use.
    public TCPEchoClient(String hostname) throws Exception {
        try{
            // The well-known port of the TCP echo service.
            final int EchoPort = 7;
            socket = new Socket(hostname,EchoPort);
        }
        catch(UnknownHostException e){
            throw new Exception("Unknown host: "+e.getMessage());
        }
        catch(IOException e){
            throw new Exception("IOException on socket creation: "+e.getMessage());
        }
    }

        // Send the sample strings to the echo server and read
        // back the responses.
    public void run(String[] sampleStrings) {
        Socket echo = getSocket();

        try{
            // Wrap the input stream in a BufferedReader.
            BufferedReader reader = new BufferedReader(
                        new InputStreamReader(echo.getInputStream()));
            // Wrap the output stream in a BufferedWriter.
            BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(echo.getOutputStream()));

            // Send each string and read the response.
            for(int i = 0; i < sampleStrings.length; i++){
                String sample = sampleStrings[i];
                System.out.println("Sending: "+sample);

                writer.write(sample);
                writer.newLine();
                // Make sure the data is flushed to the stream.
                writer.flush();

                // Read the response.
                String response = reader.readLine();
                System.out.println("The response is: "+response);
            }
            // Close the connection now it is finished with.
            echo.close();
        }
        catch(IOException e){
            System.err.println(e.getMessage());
        }
    }

    protected Socket getSocket(){
        return socket;
    }

    private final Socket socket;
}
