/**
 * An application which demonstrates how to implement a telnet client
 * using sockets.
 *
 * Example: java Telnet smtp.univ-lyon1.fr 25
 *
 * Note: this is a very simple telnet client, which only works on a
 * line by line basis.
 *
 * @version	$Id: Telnet.java,v 1.1 2003/01/15 08:07:19 nthiery Exp $
 * @author	Nicolas M. Thiéry <nthiery@users.sourceforge.net>
**/

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

public class Telnet {
    public static void main(String args[]) {

	// Get the hostname and port number from command line
	if (args.length!=2) {
	    System.out.println("Usage: java Telnet <host> <port>");
	    System.exit(1);
	}
	String host=args[0];
	int port=Integer.parseInt(args[1]);

	// Standard input
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

	try {  // Protection against failures of network operations

	    System.err.println("Connecting on server on "+host+" port "+port);
	    Socket serverSocket = new Socket("localhost", port);
	    System.err.println("Connected");

	    // Open input and output streams from the socket
	    BufferedReader inputStream = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
	    PrintStream     outputStream = new PrintStream(serverSocket.getOutputStream());

	    String line;
	    while(true) {
		System.out.print("Input: ");
		line = in.readLine();
		if (line==null) { break; };
		outputStream.println(line);
		line = inputStream.readLine();
		if (line==null) { break; };
		System.out.println("Answer: "+line);
	    }

	}
	catch (IOException e) {
	    System.out.println(e);
	    return;
	}
    }
}
