// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

import org.apache.commons.net.telnet.TelnetClient;

public class Telnet {
    public static void main(String[] args) throws Exception {
        TelnetClient tc = new TelnetClient("vt100");
        tc.connect("xxxx");
        BufferedReader br = new BufferedReader(new InputStreamReader(tc.getInputStream()));
        Thread t = new TelnetReader(br);
        t.start();
        PrintStream ps = new PrintStream(tc.getOutputStream());
        Thread.sleep(1000);
        sendCommand(ps, "xxxx");
        sendCommand(ps, "xxxx");
        Thread.sleep(1000);
        sendCommand(ps, "ls -l");
        sendCommand(ps, "logout");
        t.join();
        tc.disconnect();
    }
    private static void sendCommand(PrintStream ps, String cmd) throws InterruptedException {
        Thread.sleep(00);
        ps.println(cmd);
        ps.flush();
    }
}

class TelnetReader extends Thread {
    private BufferedReader br;
    public TelnetReader(BufferedReader br) {
        this.br = br;
    }
    public void run() {
        try {
            String line;
            while((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // nothing
        }
    }
}
