Java FTP protocol-level client implementation

Source: Internet
Author: User
Tags ftp file ftp client ftp protocol
10.2.4.3 Example 3: network application layer protocol developmentTsinghua University Press "Java programmers, work that thing" Author: bell-Chapter 10th "master high cainiao have many dishes" part excerpt.
You may have used FTP upload and download tools. For example, "LeapFTP" is a convenient FTP server upload and download tool ,. This tool is very convenient. after entering the user name and password, you can see the file list on the FTP server for easy upload and download operations.

Have you ever tried writing an FTP file upload and download application in Java?
Java can also develop such a program, which is not complex. Let's first look at how FTP application development is made using the Java FTP toolkit. See the following program:
Import sun.net .*;
Import sun.net. FTP. *; public class FTP {

Public static void main (string [] ARGs ){

String Server = "192.168.0.12"; // enter the IP address of the FTP server.
String user = "useway"; // username used to log on to the FTP server
String Password = "! @ # $ % Abce "; // password of the username used to log on to the FTP server
String Path = "/home/useway"; // path on the FTP server

Try {

Ftpclient = new ftpclient (); // create an ftpclient object
Ftpclient. openserver (server); // connect to the FTP server
Ftpclient. login (user, password); // log on to the FTP server

If (path. Length ()! = 0) ftpclient. Cd (PATH );

Telnetinputstream is = ftpclient. List ();
Int C;
While (C = is. Read ())! =-1 ){
System. Out. Print (char) C );
}
Is. Close ();
Ftpclient. closeserver (); // exit the FTP server
}
Catch (exception ex ){
}
}
} If you are interested, you can write this program by yourself. When the program runs, we will see the directory content of the server program.


This program is a simple program for obtaining the FTP Server File List, but do not misunderstand it. This program cannot be called the development of the "network application layer protocol" program!
This program only uses "sun.net. *; "and" sun.net. FTP. *; "in the related class for FTP operations, we did not use Java Socket to send any request to the FTP server at the network layer, but through the Java toolkit, the connection request sent to the server.
The advantage of using the Java FTP package to connect to the FTP server is that we don't need to care about the details of sending data on the network layer, but just call the corresponding method. The disadvantage of using a Java FTP package to connect to an FTP server is that developers do not know the ins and outs of application-layer protocol sending and receiving, do not understand the principles, and have a weak grasp of the underlying data.
Some programmers will ask: "How does FTP interact with the PC and server on the network layer ?", Okay. Let's list the FTP protocol interaction process.

See the following FTP protocol interaction example:
FTP server: 220 (vsftpd 2.0.1)
FTP Client: User useway
FTP server: 331 please specify the password.
FTP Client: pass! @ # $ % Abce
FTP server: 230 login successful.
FTP Client: CWD/home/useway
FTP server: 250 directory successfully changed.
FTP Client: epsv all
FTP server: 200 epsv all OK.
FTP Client: epsv
FTP server: 229 entering extended passive mode (||| 62501 |)
FTP Client: List
The FTP server: 150 here comes the directory listing.
FTP server: 226 directory send OK.
FTP Client: Quit
FTP server: 221 goodbye.
The above text is actually the process of interaction between the FTP server and the FTP client. The protocol for transmitting information between them is the TCP protocol, and the content sent to each other is the content written in the above text.Next we will gradually explain the meaning of each sentence:

FTP server: 220 (vsftpd 2.0.1) | Description: the connection is successful.
FTP Client: User useway | Description: User Name
FTP server: 331 please specify the password. | Description: enter the password.
FTP Client: pass! @ # $ % Abce | Description: enter the password.
FTP server: 230 login successful. | Description: logon successful
FTP Client: CWD/home/useway | Description: Switch the directory.
FTP server: 250 directory successfully changed. | Description: The Directory is successfully switched.
FTP Client: epsv all | Description: passive link of epsv
FTP server: 200 epsv all OK. | Description: OK
FTP Client: epsv | Description: Link
FTP server: 229 entering extended passive mode (||| 62501 |) | Description: The Passive connection port is 62501.
FTP Client: List | Description: Execute the list to display the file list
FTP server: 150 here comes the directory listing. | Description: The list is sent from Port 62501.
FTP server: 226 directory send OK. | Description: sending completed
FTP Client: Quit | Description: Exit FTP
FTP server: 221 goodbye. | Description: Goodbye
With the above text content, we can get the FTP file list without any tools. Do not believe that you will follow me again.
  Step 1: First open cmd to enter the doscommand line mode, and type:Telnet 192.168.0.1 21 [Press enter] Note: Telnet to port 21 of the FTP server. The result obtained after the command is executed. Have you found any problems?
The prompt content is exactly the first sentence in the above text: 220 (vsftpd 2.0.1). This indicates that the FTP server has accepted our link and can proceed to the next step. Step 2: type the following series of sent content one by one:User useway [Press enter]
Pass! @ # $ % Abce [Press enter]
CWD/home/useway [Press enter]
Epsv all [Press enter]
Epsv [Press enter]
  The result. Well, this time the FTP server gave a series of responses, and finally gave a new port number "58143 ". Step 3: open a new cmd window and type:Telnet 192.168.0.1 58143 [Press enter] Note: The port number connecting to the server in this Telnet request is "58143", which is a link port that the FTP server gives us. After the link, the window is blank without any prompts ,. Step 4: return to the first cmd window and type:List [Press enter] Step 5: At this time, the second cmd window will receive the file list:  The second window receives the file list. Step 6: ExitQuit [Press enter] After the execution is complete, the connection to the host is lost ,. As you can see, the FTP protocol is such an interactive process. Using the system's built-in Telnet tool, you can also perform FTP operations on these basic commands. If you want to use a Java Socket to complete the above operations, you only need to send a string to the FTP server step by step according to the above content.
The following is an example code: Import java. Io. inputstream;
Import java. Io. outputstream;
Import java.net. Socket; public class ftpclient {
Public static void main (string [] ARGs) throws exception {
Socket socket = new socket ("192.168.0.1", 21 );
Inputstream is = socket. getinputstream ();
Outputstream OS = socket. getoutputstream (); // receives the initial link information
Byte [] buffer = new byte [100];
Int length = is. Read (buffer );
String S = new string (buffer, 0, length );
System. Out. println (s );
// Sending User Name
String STR = "User useway/N ";
OS. Write (Str. getbytes ());
// Obtain the returned value
Length = is. Read (buffer );
S = new string (buffer, 0, length );
System. Out. println (s );
// Send the password
STR = "pass! @ # $ % ABCD/N ";
OS. Write (Str. getbytes ());
// Obtain the returned value
Length = is. Read (buffer );
S = new string (buffer, 0, length );
System. Out. println (s );
// Send the switch folder command
STR = "CWD/home/useway/N ";
OS. Write (Str. getbytes ());
// Obtain the returned value
Length = is. Read (buffer );
S = new string (buffer, 0, length );
System. Out. println (s );
// Set the Mode
STR = "epsv all/N ";
OS. Write (Str. getbytes ());
// Obtain the returned value
Length = is. Read (buffer );
S = new string (buffer, 0, length );
System. Out. println (s );
// Obtain the passive listener Information
STR = "epsv/N ";
OS. Write (Str. getbytes ());
// Obtain the returned value
Length = is. Read (buffer );
S = new string (buffer, 0, length );
System. Out. println (s );
// Obtain the port number of the FTP passive listener
String portlist = S. substring (S. indexof ("(|") + 4, S. indexof ("| )"));
System. Out. println (portlist );
// Instantiate the showlist Thread class and link to the FTP passive listening port number
Showlist SL = new showlist ();
SL. Port = integer. parseint (portlist );
SL. Start ();
// Execute the LIST Command
STR = "list/N ";
OS. Write (Str. getbytes ());
// Obtain the returned value
Length = is. Read (buffer );
S = new string (buffer, 0, length );
System. Out. println (s );
// Close the link
Is. Close ();
OS. Close ();
Socket. Close ();
}
}
// Obtain the passive link information class, which is Multithreading
Class showlist extends thread {
Public int Port = 0;
Public void run (){
Try {
Socket socket = new socket ("192.168.0.1", this. Port );
Inputstream is = socket. getinputstream ();
Outputstream OS = socket. getoutputstream ();
Byte [] buffer = new byte [10000];
Int length = is. Read (buffer );
String S = new string (buffer, 0, length );
System. Out. println (s );
// Close the link
Is. Close ();
OS. Close ();
Socket. Close ();
}
Catch (exception ex ){
}
}
} The running result obtained after the program is run is basically the same as the running result above. What about the underlying layer is nothing more than the encapsulated methods, as long as we understand the rules they run, we can develop the same program ourselves.
This article is a section of "Java programmer, work day" by Tsinghua University Press. (Reprinted please keep this sentence, thank you !)  

Java programmers:
Preface,Directory
Zhuo Yue network sales Link
China-Pub sales Link
Dangdang sales LinkCommemorative post on "Java programmer, work day"

Download an electronic version of "Java programmer, work day"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.