Implement FTP server with Java

xiaoxiao2021-03-05  21

FTP command

The main operation of FTP is based on various commands. Commonly used orders are:

◆ Set the transfer mode, which includes ASCII (text) and binary binary mode;

◆ Directory operation, 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 to the remote computer; the close command is used to turn off the connection;

◆ Send operation, the put command is used to transfer files to remote computers; the MPUT command is used to transmit multiple files to remote computers;

◆ Get operation, the get command is used to receive a file; the MGET command is used to receive multiple files.

Programming ideas

According to the working principle of FTP, establish a server socket port in the main function, waiting for the client request, once the client request is accepted, the server program creates a server division thread, processing the client's command. If the client needs to transfer the file transfer with the server, create a new socket connection to complete the operation of the file.

Programming skills

Main function design

In the main function, complete the creation of the listening and service thread of the server port. We use a static string variable initdir to save the work directory where the server thread is running. The server's initial working directory is the root directory that the user is entered by the user, default is the root directory of the C disk.

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 {innitdir = "c:";

INT i = 1;

Try {

System.out.println ("FTP Server Started!");

// Listening to port of the 21st number

Serversocket S = New ServerSocket (21);

For (;;) {

/ / Accept client request

Socket incoming = S.Accept ();

// Create service thread

New ftpserver (incoming, i) .Start ();

i ;

}

} catch (exception e) {}

}

2. Design of thread class

The main designs of thread classes are implemented in the RUN () method. Use the run () method to get the client socket information, get the input stream and output stream according to the socket, send welcome information to the client.

3. Processing of ftp command

(1) Access control command

◆ User name (user) and password (pass) command processing code 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 username and password entered by the client user.

◆ CWD (CHANGE WORKING DIRECTORY) command processing 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 work directory to the directory specified by the user.

◆ CDUP (CHANGE TO PARENT DIRECTORY) command processing code is 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 as the last layer 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) Transfer 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 a client to receive 32-bit IP addresses and 16-bit TCP port numbers for data. This information is used in 8 bits, using decimal transmission, separated by commas in the middle.

◆ TYPE command processing code is as follows:

IF (Str.StartSwith ("Type")) {

OUT.PRINTLN ("200 Type Set");

}

Use the TYPE command to complete the type setting.

(3) FTP service command

◆ Retrick and Store (Store) code processing code

IF (Str.StartSwith ("retr")) {

Out.println ("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 Bytebuffler [] = 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.println ("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 Bytebuffler [] = 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) {}

}

The file transfer command includes obtaining file retri from the server and sending a file STOR in the server, the processing of these two commands is very similar. When processing the retr command, first get the name of the file to be obtained, create a file input stream based on the name, then establish a temporary socket connection with the client, and get an output stream. Subsequently, the data in the file input stream is read out and sent to the client by means of the socket output stream. After the transfer is completed, the flow and temporary socket are closed.

The processing of the Stor command is also the same process, but the direction is just the opposite.

◆ 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 the specified file on the server.

◆ List command processing code 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 string start = "";

For (int I = 0; IIF (Dirstructure [i] .indexof (".") == -1) {

Strtype = "d";

Else

{straType = "-";

Out2.println (StrtYPE DIRSTRUCTURE [I]);

}

Tempsocket.close ();

OUT.PRINTLN ("226 Transfer Complete");

}

Catch (IOException E) {}

The list command is used to return a directory structure in the working directory in the client, including a list of files and directories. When you handle this command, create a temporary socket to send directory information to the client. The destination port number of this socket defaults to 1, then create a file object for the current working directory, use the list () method of the object to get a string array containing all files and subdirectory names in the directory, and then according to the name Whether to include "." To distinguish directories and files. Finally, the obtained name array is sent to the client through the temporary socket.

转载请注明原文地址:https://www.9cbs.com/read-39000.html

New Post(0)