Implementing FTP server Solution _jsp Programming with Java

Source: Internet
Author: User
Tags parent directory thread class port number server port
FTP command

The main operations of FTP are based on a variety of commands. The common commands are:

· Sets the transfer mode, which includes Ascⅱ (text) and binary binary mode;

· Directory operations, changing or displaying the current directory of the remote computer (CD, Dir/ls command);

· Connection operation, the Open command is used to establish a connection to a remote computer;

· The send operation, the put command is used to transfer files to a remote computer; The mput command is used to transfer multiple files to a remote computer;

· Gets the operation where the get command receives a file; The Mget command is used to receive multiple files.

  Programming Ideas

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

  Programming Skills Description

1. Main function Design

In the main function, complete the server port listening and service thread creation. We use a static string variable Initdir to hold the working directory where the server thread is running. The initial working directory of the server is entered by the user at runtime, and the default is the root directory of 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{Initdir = "C:";}
int i = 1;
try{
SYSTEM.OUT.PRINTLN ("FTP Server started!");
Listen for Port 21st,
ServerSocket s = new ServerSocket (21);
for (;;) {
Accept client Requests
Socket incoming = S.accept ();
Creating a service Thread
New Ftpserver (Incoming,i). Start ();
i++;
}
}catch (Exception e) {}
}

2. Thread class Design

The main design of a thread class is implemented in the run () method. Use the Run () method to get the socket information of the client, get input stream and output stream according to socket, send welcome information to client.

3. FTP command Processing

(1) Access control command

· The user name (user) and password (pass) command handles the following code:

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 respectively to submit the username and password entered by the client user.

· The CWD (change WORKING DIRECTORY) command handles the following code:

if (Str.startswith ("CWD")) {
String str1 = str.substring (3);
DIR = dir+ "/" +str1.trim ();
Out.println ("CWD command succesful");
}

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

· The Cdup (change to PARENT DIRECTORY) command handles the following code:

if (Str.startswith ("Cdup")) {
int n = dir.lastindexof ("/");
dir = dir.substring (0,n);
Out.println ("CWD command succesful");
}

This command changes the current directory to the previous level directory.

· The QUIT command handles the following code:

if (Str.startswith ("QUIT")) {
Out.println ("Good BYE");
Done = true;
}

This command exits and closes the connection to the server, outputting good BYE.

(2) Transmission Parameters Command

· The port command handles code as follows:

if (Str.startswith ("PORT")) {
Out.println ("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 +integer.parseint (STR2);
}

When this command is used, the client must send a 32-bit IP address and a 16-bit TCP port number that the client uses to receive data. This information is in a 8-bit group, using decimal transmission, separated by commas.

· The type command handles the following code:

if (Str.startswith ("TYPE")) {
OUT.PRINTLN ("type set");
}

The type command is used to complete the types setting.

(3) FTP Service command

· Code processed by RETR (Reteieve) and store (store) commands

if (Str.startswith ("RETR")) {
Out.println ("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 ("Transfer complete");
Outfile.close ();
Tempsocket.close ();
}
catch (IOException e) {}
}
if (Str.startswith ("STOR")) {
Out.println ("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 ("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, and the processing of these two commands is very similar. When processing the RETR command, you first get the name of the file that the user wants to obtain, create a file input stream based on the name, and then establish a temporary socket connection with the client and get an output stream. Then, the data in the file input stream is read out and sent to the client with the help of the socket output stream, and the stream and the temporary socket are closed after the transmission is complete.

The processing of the STOR command is also the same process, except that the direction is just the opposite.

· The DELE (DELETE) command handles the following code:

if (Str.startswith ("DELE")) {
str = str.substring (4);
str = Str.trim ();
File File = new file (DIR,STR);
Boolean del = File.delete ();
OUT.PRINTLN ("Successful delete command");
}

The DELE command deletes the specified file on the server.

· The list command handles the following code:

if (Str.startswith ("LIST")) {
try{
Out.println ("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 ("Transfer complete");
}
catch (IOException e) {}

The list command is used to return the directory structure of the working directory in the server to the client, including a listing of files and directories. When processing this command, first create a temporary socket to send directory information to the client. The destination port number for this socket defaults to 1 and then creates a file object for the current working directory, using the object's list () method to obtain a string array containing all the file and subdirectory names in the directory, and then depending on whether the name contains "." That is unique in the filename. To differentiate between directories and files. Finally, the resulting array of names is sent to the client via 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.