Friday, July 24, 2009

Simple Old Technology

Yesterday I had an idea to write an FTP client in Java. I have always known that this is a simple old piece of technology. Old, but still widely used until now. I don't understand why Sun doesn't have a simple implementation in its Java Standard Edition.
Anyway, I remembered that there was an RFC on FTP. A little bit of googling got me the paper that I wanted, RFC 959. To be honest, it wasn't as simple as I would expect it to be. That didn't stop me from starting coding. The first thing that came to my mind was to create a Socket to an FTP server on port 21 and start sending FTP commands.

Socket ftpclient = new Socket("ftp.someserver.com", 21);
InputStream is = ftpclient.getInputStream();
do {
byte[] b = new byte[1024];
int len = is.read(b);
System.out.println(new String(b, 0, len));
} while (is.available() > 0);

Next, I tried logging in. I quickly found out that you had to end each command with CRLF (\r\n).

OutputStream os = ftpclient.getOutputStream();
os.write("USER anonymous\r\n".getBytes());
// readInputStream . . .
os.write("PASS guest\r\n".getBytes());
// readInputStream . . .
os.write("QUIT\r\n".getBytes());
// readInputStream . . .

No comments:

Post a Comment