Implement FTP Server solution using Java

Source: Internet
Author: User

FTP command

The main FTP operations are based on various commands. Common Commands include:

· Set transmission mode, which includes ASC Ⅱ (text) and BINARY mode;

· Directory operations: change or display the current directory of the remote computer (cd, dir/ls command );

· Connection operation. The open command is used to establish a connection with a remote computer. The close command is used to close the connection;

· Sending operation. The put command is used to send files to a remote computer. The mput command is used to send multiple files to a remote computer;

· Get operation. The get command is used to receive a file. The mget command is used to receive multiple files.

 Programming Logic

According to the working principle of FTP, create a server socket port in the main function and wait for the client request. Once the client request is accepted, the server program will establish a server thread separation to process client commands. If the client needs to transfer files with the server, a new socket connection is established to complete file operations.

 Programming Skills

1. Main Function Design

In the main function, listener the server port and create a service thread. We use a static string variable initDir to save the working directory of the server line runtime. The initial working directory of the server is input by the user when the program is running. The default is the root directory of drive C.

The specific code is as follows:

Public class ftpServer extends Thread {
Private Socket socketClient;
Private int counter;
Private static String initDir;
Public static void main (String [] args ){
If (args. length! = 0 ){
InitDir = args [0];
} Else {initDir = "c :";}
Int I = 1;
Try {
System. out. println ("ftp server started! ");
// Listen to port 21
ServerSocket s = new ServerSocket (21 );
For (;;){
// Accept client requests
Socket incoming = s. accept ();
// Create a service thread
New ftpServer (incoming, I). start ();
I ++;
}
} Catch (Exception e ){}
}

2. Thread class design

The main design of the thread class is implemented in the run () method. Use the run () method to obtain the socket information of the client, obtain the input stream and output stream based on the socket, and send the welcome information to the client.

3. FTP command processing

(1) access control commands

· The code for processing the user name (user) and password (pass) commands is as follows:

If (str. startsWith ("USER ")){
User = str. substring (4 );
User = user. trim ();
Out. println ("331 Password ");
}
If (str. startsWith ("PASS "))
Out. println ("230 User" + user + "logged in .");

The User command and the Password command are used to submit the User name and Password entered by the client User respectively.

· The CWD (change working directory) command Process Code is as follows:

If (str. startsWith ("CWD ")){
String str1 = str. substring (3 );
Dir = dir + "/" + str1.trim ();
Out. println ("250 CWD command succesful ");
}

This command changes the working directory to the user-specified directory.

· The CDUP (change to parent directory) command process the Code as follows:

If (str. startsWith ("CDUP ")){
Int n = dir. lastIndexOf ("/");
Dir = dir. substring (0, n );
Out. println ("250 CWD command succesful ");
}

This command changes the current directory to the previous directory.

· The QUIT command processing code is as follows:

If (str. startsWith ("QUIT ")){
Out. println ("good bye ");
Done = true;
}

This command exits and closes the connection with the server, and outputs good bye.

(2) transmission parameter command

· The Port command processing code is as follows:

If (str. startsWith ("PORT ")){
Out. println ("200 PORT command successful ");
Int I = str. length ()-1;
Int j = str. lastIndexOf (",");
Int k = str. lastIndexOf (",", J-1 );
String str1, str2;
Str1 = "";
Str2 = "";
For (int l = k + 1; lstr1 = str2 + str. charAt (l );
}
For (int l = j + 1; l <= I; l ++ ){
Str2 = str2 + str. charAt (l );
}
TempPort = Integer. parseInt (str1) * 16*16 + Integer. parseInt (str2 );
}

When using this command, the client must send the 32-bit IP address used by the client to receive data and the 16-bit TCP port number. The information is transmitted in decimal format and separated by commas.

· The TYPE command processing code is as follows:

If (str. startsWith ("TYPE ")){
Out. println ("200 type set ");
}

The TYPE command is used to complete the TYPE setting.

(3) FTP service commands

· Code processed by RETR (RETEIEVE) and STORE (STORE) commands

If (str. startsWith ("RETR ")){
Out. printlns ("150 Binary data connection ");
Str = str. substring (4 );
Str = str. trim ();
RandomAccessFile outFile = new
RandomAccessFile (dir + "/" + str, "r ");
Socket tempSocket = new Socket (host, tempPort );
OutputStream outSocket = tempSocket. getOutputStream ();
Byte byteBuffer [] = new byte [1024];
Int amount;
Try {
While (amount = outFile. read (byteBuffer ))! =-1 ){
OutSocket. write (byteBuffer, 0, amount );
}
OutSocket. close ();
Out. println ("226 transfer complete ");
OutFile. close ();
TempSocket. close ();
}
Catch (IOException e ){}
}
If (str. startsWith ("STOR ")){
Out. printlns ("150 Binary data connection ");
Str = str. substring (4 );
Str = str. trim ();
RandomAccessFile inFile = new
RandomAccessFile (dir + "/" + str, "rw ");
Socket tempSocket = new Socket (host, tempPort );
InputStream inSocket = tempSocket. getInputStream ();
Byte byteBuffer [] = new byte [1024];
Int amount;
Try {
While (amount = inSocket. read (byteBuffer ))! =-1 ){
InFile. write (byteBuffer, 0, amount );
}
InSocket. close ();
Out. println ("226 transfer complete ");
InFile. close ();
TempSocket. close ();
}
Catch (IOException e ){}
}

File Transfer Commands include obtaining file RETR from the server and Sending File STOR to the server. These two commands are very similar in processing. When processing the RETR command, first obtain the name of the file to be obtained by the user, create a file input stream based on the name, then establish a temporary socket connection with the client, and get an output stream. Then, read the data in the file input stream and send it to the client using the socket output stream. After the transmission is complete, close the stream and temporary socket.

The processing of the STOR command is the same, but the opposite is true.

· The DELE (DELETE) command processing code is as follows:

If (str. startsWith ("DELE ")){
Str = str. substring (4 );
Str = str. trim ();
File file = new File (dir, str );
Boolean del = file. delete ();
Out. println ("250 delete command successful ");
}

The DELE command is used to delete specified files on the server.

· The LIST command processing code is as follows:

If (str. startsWith ("LIST ")){
Try {
Out. println ("150 ASCII data ");
Socket tempSocket = new Socket (host, tempPort );
PrintWriter out2 = new PrintWriter (tempSocket. getOutputStream (), true );
File file = new File (dir );
String [] dirStructure = new String [10];
DirStructure = file. list ();
String strType = "";
For (int I = 0; iif (dirStructure [I]. indexOf (".") =-1) {strType = "d ";}
Else
{StrType = "-";}
Out2.println (strType + dirStructure [I]);
}
TempSocket. close ();
Out. println ("226 transfer complete ");
}
Catch (IOException e ){}

The list command returns the directory structure under the working directory of the server to the client, including the LIST of files and directories. When processing this command, create a temporary socket to send the directory information to the client. The default port number of this socket is 1, and then a File object is created for the current working directory () method to obtain a string array containing the names of all files and sub-directories in the directory, and then determine whether the name contains the Special ". to distinguish between directories and files. Finally, the obtained name array is sent to the client through a temporary socket.

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.