package TcpExamples;

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

/**
 * Before, we always used telnet to connect to the server. Here we are now
 * writing our own program to do the connection.
 *
 * As you will see, when we run this after we start the server we will see the
 * same string telnet printed, sent by the server. The output at the server will
 * show different socket pairs for each time we ran it.
 *
 * @author mcgredo
 */
public class TcpExample3Client {

	// IPv6 String constant for localhost address, similarly IPv4 127.0.0.1
	public final static String LOCALHOST = "0:0:0:0:0:0:0:1"; 

	public static void main(String[] args) {
		try {
			while (true) {
				System.out.println("TcpExample3Client creating socket...");

				// We request an IP to connect to ("localhost") and
				// port number at that IP (2317). This establishes
				// a connection to that IP in the form of the Socket
				// object; the server uses a ServerSocket to wait for
				// connections.
				Socket socket = new Socket(LOCALHOST, 2317); // locohost?

				// Now hook everything up (i.e. set up the streams), Java style:
				InputStream       is  =     socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader     br = new BufferedReader(isr);

				// Read the single line written by the server. We'd
				// do things a bit differently if many lines to be read
				// from the server, instead of one only.
				String serverMessage = br.readLine();
				System.out.println("==================================================");
				System.out.println("Now we're talking!");
				System.out.println("The message the server sent was " + serverMessage);
				// socket gets closed, either automatically/silently this code (or possibly by server)
			} // end while(true)
		} 
		catch (IOException e) {
			System.out.println("Problem with client: "); // describe what is happening
			System.out.println(e);
            // Provide more helpful information to user if exception occurs due to running twice at one time
            if (e instanceof java.net.BindException)
                System.out.println("*** Be sure to stop any other running instances of this program!");
		}
		// program exit: tell somebody about that
		System.out.println("client exit");
	}
}