import java.io.*; import java.net.*; /** * Vernetzte Systeme, Uebung 6, Aufgabe 25 * @author Markus Keller */ public class FTPClient { public static final boolean OK = true; public static final boolean TERMINATED = false; public static int state = 0; public static Socket socket; public static PrintWriter out; public static BufferedReader in; /** * Implements the finite state machine (endlicher Zustandsautomat). * @param s a reply line from the FTP-Server * @return OK or TERMINATED */ public static boolean handleInput (String s) { // certainly not a state code (too short) if (s.length() < 3) return OK; if (!Character.isDigit (s.charAt(0))) return OK; // is it a comment? ('-' after state code) if (s.charAt(3) == '-') return OK; String code = s.substring(0,3); switch(state) { case 0: if (code.equals("220")) { send("USER ftp"); state = 1; return OK; } else { error(code); state = 5; return TERMINATED; } case 1: if (code.equals("331")) { send("PASS foo@inf.ethz.ch"); state = 2; } else { send("QUIT"); state = 4; } return OK; case 2: if (code.equals("230")) { send("STAT"); state = 3; } else { send("QUIT"); state = 4; } return OK; case 3: if (code.equals("211")) { send("QUIT"); state = 4; } else { send("QUIT"); state = 4; } // exercice: shorten case 3 ;-) return OK; case 4: if (code.equals("221")) { state = 5; } else { error(code); state = 5; } return TERMINATED; case 5: System.out.println("normal beendet."); return TERMINATED; default: System.out.println("illegaler Zustand: " + code); return TERMINATED; } } static void send(String ftpCommand) { out.println(ftpCommand); System.out.print("state " + state); // may be commented out... System.out.println("> " + ftpCommand); } static void error(String inLine) { System.err.println("falsche Eingabe: " + inLine); } /** * Usage: java FTPClient */ public static void main(String[] args) throws Exception { socket = new Socket(args[0], 21); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(socket.getInputStream())); String fromServer; while ((fromServer = in.readLine()) != null) { //System.out.println("Server: " + fromServer); System.out.println(fromServer); if (handleInput(fromServer) == TERMINATED) { break; } } out.close(); in.close(); socket.close(); } }