Multi-thread FTP download using Java

Source: Internet
Author: User
Tags ftp client

1: byte stream structure:
Send 12 + 1024 bytes each time
The first seven bytes indicate commands.
The length of the valid byte in the last 12th bytes from the seventh to 1024 bytes
For example, if the content of the first 12 bytes in a frame is "upfilen00012", the file name to be uploaded is 12 characters in length. Then the program will remove 12 bytes from the next 1024 bytes and convert it into a string as the file name to be uploaded.

2: Command Structure
Server:
Disconn: disconnect
Lsfiles: Send the current directory file list
Endfile: indicates the end mark of a file to be uploaded.
Upfilen: indicates that a new file is to be uploaded and the file name is included in this package.
Updatas: indicates the data to be uploaded.
Dnfilen: indicates the name of the file to be downloaded. The server needs to transfer the file to the client.
Client:
Disconn: disconnect
Lsfiles: list of files in the current directory of the receiving server
Endfile: Download The End mark of an object
Dndatas: indicates the data to be downloaded.

3: file structure
Ftpserver: FTP software server, which is currently listening on port 2121, supports multithreading, file upload, download, and list.
Ftpclient: FTP client, which is connected to the server of the Local Machine by default. It supports file upload, download, and list on port 2121.
Ftpclientui: the user interface of the FTP client, which is completely written by swing and not automatically generated by JB.
Publicfunc: provides some public static methods, such as assembling a given String object into a frame to be sent. Format the number into a five-character string object.
Package cn.edu. Bit. Software. ftptrans;

Import java. Io .*;
Import java.net .*;
Import java. util. vector;
Import java. util. Logging .*;

Public class ftpserver
{
// Client socket object
Private serversocket m_servsocket;

// Port Number of the FTP server
Private int server_port;

// Maximum number of connections allowed by the FTP server
Private int max_conn;

// The connected client processes the object manager.
Private vector vecclient;

// Set a log object
Private logger mylog;

Private consolehandler handler;

String strservhome;

Public ftpserver (INT servport, int maxconn)
{
Server_port = servport;
Max_conn = maxconn;
Strservhome = "C ://";
Vecclient = new vector ();
/* ------------ Initialize log ------------*/
Try
{
Handler = new consolehandler ();
Handler. setlevel (level. All );
Mylog = logger. getlogger ("ftpserver ");
Mylog. addhandler (handler );
Mylog. setlevel (level. All );
}
Catch (securityexception E)
{
Mylog. Warning ("exception occurred when setting the program Log Level ");
Mylog. Warning (E. getmessage ());
}

/* -------------- Initialize the server, port 2121 ----------------------*/
Try
{
M_servsocket = new serversocket (server_port, max_conn );
While (true)
{
Mylog. Finest ("ftpserver listening on port 2121 ");
Socket clientsocket = m_servsocket.accept ();
Vecclient. Add (clientsocket );
Mylog.info ("#" + vecclient. Size () + "Connect client ");
New transhandler (this, clientsocket, vecclient. Size (). Start ();
}
}
Catch (ioexception E)
{
Mylog. Warning ("error occurred during FTPServ initialization ");
Mylog. Warning (E. getmessage ());
}
}

Public void deleteclient (transhandler handler)
{
Try
{
Vecclient. Remove (handler );
Vecclient. setsize (vecclient. Size ()-1 );
Mylog.info ("#" + handler. iclientnum + "client disconnected from the server! ");
}
Catch (exception E)
{
Mylog. Warning ("exception occurred when deleting the #" + handler. iclientnum + "client ");
Mylog. Warning (E. getmessage ());
}
}

Public static void main (string [] ARGs)
{
New ftpserver (2121, 50 );
}
}

/**
* Class for processing client requests when a client is connected
* @ Author findfrog
* @ Version 1.0
*/
Class transhandler extends thread
{
// Server handle, used to destroy the transhandler object
Ftpserver main = NULL;
// Client socket
Private socket m_clientsocket = NULL;

// Log object
Private logger mylog;

// File path to be uploaded
Private string strupfilepath = NULL;

// File path to download
Private string strdnfilepath = NULL;

// Serial number of the Client
Int iclientnum =-1;

// Buffer the size of byte data
Private int ibufferlength;

// Buffer byte array
Byte [] inputbytes;

// Commands sent from the client
String strclientorder;
// Obtain the input information from the socket.
Inputstream m_inputstream;
// Output stream to socket
Outputstream m_outputstream;
// Output stream used to upload files
Fileoutputstream m_fileoutputstream;
// Input stream used to download an object
Fileinputstream m_fileinputstream;

// Constructor
Public transhandler (ftpserver fserver, socket S, int inum)
{
Try
{
Main = fserver;
// Pay the client socket handle to the local object
M_clientsocket = s;
// Initialize the log object
Mylog = logger. getlogger ("transhandler ");
// Initialize the client serial number
Iclientnum = inum;
// Obtain the input information from the socket.
M_inputstream = m_clientsocket.getinputstream ();
M_outputstream = m_clientsocket.getoutputstream ();
Ibufferlength = 1024;
Inputbytes = new byte [ibufferlength + 12];

}
Catch (exception E)
{
Mylog. Warning ("an exception occurred when initializing transhandler! ");
Mylog. Warning (E. getmessage ());
}
}

Public void run ()
{
Try
{
Int ilength;
While (ilength = m_inputstream.read (inputbytes, 0, 12 + ibufferlength ))! =
-1)
{
Strclientorder = new string (inputbytes, 0, 7 );
If (strclientorder. Equals ("disconn "))
{// Disconnect
Mylog.info ("Get disconn ");
Exit ();
}
Else if (strclientorder. Equals ("lsfiles "))
{// Send the current directory file list
Mylog.info ("the server receives the lsfiles command ");
File flhome = new file (main. strservhome );
String [] strfilenames = flhome. List ();
Strfilenames = adjuststrings (strfilenames );
For (INT I = 0; I <strfilenames. length; I ++)
{
String strfilenamelength = publicfunc. formatlength (strfilenames [I].
Getbytes (). Length );
Byte [] filenamebytes = strfilenames [I]. getbytes ();
Byte [] outbytes = publicfunc. makepackage ("lsfiles ",
Strfilenamelength, filenamebytes );
M_outputstream.write (outbytes, 0, outbytes. Length );
M_outputstream.flush ();
}
}
Else if (strclientorder. Equals ("endfile "))
{// Upload the end mark of a file
Mylog.info ("receiving the end symbol of a file ");
M_fileoutputstream.close ();
}
Else if (strclientorder. Equals ("upfilen "))
{// Indicates that a new file is to be uploaded and the package contains the file name.
Int ifilenamelength = integer. parseint (new string (inputbytes, 7, 5 ));
Mylog.info ("the length of the file name to be uploaded is" + ifilenamelength );
String strfilename = new string (inputbytes, 12, ifilenamelength );
Mylog.info ("the file name to be uploaded is:" + strfilename );
// Initialize the Upload File Path
Strupfilepath = Main. strservhome + strfilename;
File upfile = new file (strupfilepath );
M_fileoutputstream = new fileoutputstream (upfile );
}
Else if (strclientorder. Equals ("updatas "))
{// Indicates that the package is the data to be uploaded.
// The length of the current packet
Mylog.info ("receiving files ...");
Int idatalength = integer. parseint (new string (inputbytes, 7, 5 ));
M_fileoutputstream.write (inputbytes, 12, idatalength );
M_fileoutputstream.flush ();
}
Else if (strclientorder. Equals ("dnfilen "))
{// Indicates the file name to be downloaded. The server needs to transfer the file to the client.
Int ifilenamelength = integer. parseint (new string (inputbytes, 7, 5 ));
Mylog.info ("the length of the file name to be downloaded is" + ifilenamelength );
String strfilename = new string (inputbytes, 12, ifilenamelength );
Mylog.info ("the name of the file to be downloaded is:" + strfilename );
// Initialize the Upload File Path
Strdnfilepath = Main. strservhome + strfilename;
File dnfile = new file (strdnfilepath );
// Initialize the file output stream
M_fileinputstream = new fileinputstream (dnfile );

// Start transferring files to the client
Mylog.info ("starting to transfer files to the client" + strfilename + "...");
Int iinputlength = 0;
String strinputlength;
Byte [] readbytes = new byte [ibufferlength];
While (iinputlength = m_fileinputstream.read (readbytes, 0,
Ibufferlength ))! =
-1)
{
Strinputlength = publicfunc. formatlength (iinputlength );
Byte [] outbytes = publicfunc. makepackage ("dndatas", strinputlength,
Readbytes );
M_outputstream.write (outbytes, 0, outbytes. Length );
M_outputstream.flush ();
}

// Send the end mark of the last file
M_outputstream.write (publicfunc. makepackage ("endfile", "00001 ",
New byte [1]);
M_outputstream.flush ();
}
}
}
Catch (exception E)
{
Mylog. Warning (E. getmessage ());
}
}

Public void exit ()
{
Try
{
M_outputstream.write (publicfunc. makepackage ("disconn", "00001 ",
New byte [1]);
M_inputstream.close ();
M_outputstream.close ();
Main. deleteclient (this );
Main = NULL;
}
Catch (exception E)
{
Mylog. Warning ("Disconnect Client #" + this. iclientnum + "exception! ");
Mylog. Warning (E. getmessage ());
}
}

Public String [] adjuststrings (string [] strfilenames)
{
String [] stritemnames = new string [strfilenames. Length + 1];
Stritemnames [0] = "return to the upper level ";
Int J = 1;
For (INT I = 0; I <strfilenames. length; I ++)
{
File upfile = new file (main. strservhome + strfilenames [I]);
If (! Upfile. isfile ())
{
Stritemnames [J ++] = "[Folder]" + strfilenames [I];
}
}
For (INT I = 0; I <strfilenames. length; I ++)
{
File upfile = new file (main. strservhome + strfilenames [I]);
If (upfile. isfile ())
{
Stritemnames [J ++] = strfilenames [I];
}
}

Return stritemnames;
}

}

Package cn.edu. Bit. Software. ftptrans;

Import java. Io .*;
Import java.net .*;
Import java. util. Logging .*;
Import java. util. vector;

Public class ftpclient extends thread
{
Logger mylog = logger. getlogger ("ftpclient ");
Socket m_clientsocket;
// Buffer the size of byte data
Private int ibufferlength;

// Buffer byte array
Byte [] inputbytes;

Vector vecservfiles;

// Obtain the input information from the socket.
Inputstream m_inputstream;
// Output stream to socket
Outputstream m_outputstream;
// Output stream to the file where the local file is written
Fileoutputstream m_fileoutputstream;
// Input file stream for reading files from the Local Machine
Fileinputstream m_fileinputstream;
// Commands sent from the server
String strserverorder;
// Host IP Address
String strserverip;
// The port number of the server
Int iserverport;

Public ftpclient (string strservip, int iservport)
{
Strserverip = strservip;
Iserverport = iservport;
}

Public void run ()
{
Try
{
// Establish a connection
M_clientsocket = new socket (strserverip, iserverport );
Mylog.info ("connected to host" + strserverip + "on port" + iserverport );
M_inputstream = m_clientsocket.getinputstream ();
M_outputstream = m_clientsocket.getoutputstream ();
Mylog. Fine ("the client obtains the input/output stream of the socket! ");
Ibufferlength = 1024;
Inputbytes = new byte [ibufferlength + 12];
Vecservfiles = new vector ();
Dobusiness ();
}
Catch (unknownhostexception E)
{
Mylog. Warning ("Unknown Server address ");
Mylog. Warning (E. getmessage ());
}
Catch (ioexception E)
{
Mylog. Warning (E. getmessage ());
}
Catch (exception E)
{
Mylog. Warning (E. getmessage ());
}
}

Public void dobusiness ()
{
Try
{
Int ilength = 0;
While (ilength = m_inputstream.read (inputbytes, 0, ibufferlength + 12 ))! =
-1)
{
Strserverorder = new string (inputbytes, 0, 7 );
If (strserverorder. Equals ("disconn "))
{// Disconnect
Mylog.info ("disconn obtained on the client ");
Int length = integer. parseint (new string (inputbytes, 7, 5 ));
Mylog.info ("length is" + length );
}
Else if (strserverorder. Equals ("lsfiles "))
{// List of files in the current directory of the receiving server

Int idatalength = integer. parseint (new string (inputbytes, 7, 5 ));
Mylog.info ("the length of the file name on the client is:" + idatalength );
String strfilename = new string (inputbytes, 12, idatalength );
Mylog.info ("the client is obtaining the server directory information..." + strfilename );
Vecservfiles. Add (strfilename );
}
Else if (strserverorder. Equals ("endfile "))
{// Download the end mark of an object
Mylog.info ("receiving the end symbol of the downloaded file ");
M_fileoutputstream.close ();
}
Else if (strserverorder. Equals ("dndatas "))
{// Indicates that the package is the data to be downloaded.
Int idatalength = integer. parseint (new string (inputbytes, 7, 5 ));
M_fileoutputstream.write (inputbytes, 12, idatalength );
M_fileoutputstream.flush ();
}
}
}
Catch (exception E)
{

}
}

/**
* Client Upload File Name
* @ Param strfilename name of the file to be uploaded
*/
Public void upfilename (string strfilename)
{
Try
{
String strlength = publicfunc. formatlength (strfilename. getbytes (). Length );
Byte [] outbytes = publicfunc. makepackage ("upfilen", strlength,
Strfilename. getbytes ());
M_outputstream.write (outbytes, 0, outbytes. Length );
M_outputstream.flush ();
}
Catch (exception E)
{
Mylog. Warning ("an exception occurred when the client writes the file name to the server ");
Mylog. Warning (E. getmessage ());
}
}

/**
* Upload the local file strfilepath to the server
* @ Param strfilepath: local file path
*/
Public void upfiledata (string strfilepath)
{
Try
{
File file = new file (strfilepath );
M_fileinputstream = new fileinputstream (File );

Int iinputlength = 0;
String strinputlength;
Byte [] readbytes = new byte [ibufferlength];
While (iinputlength = m_fileinputstream.read (readbytes, 0,
Ibufferlength ))! =
-1)
{
Strinputlength = publicfunc. formatlength (iinputlength );
Byte [] outbytes = publicfunc. makepackage ("updatas", strinputlength,
Readbytes );
M_outputstream.write (outbytes, 0, outbytes. Length );
M_outputstream.flush ();
}
// Send the end mark of the last file
M_outputstream.write (publicfunc. makepackage ("endfile", "00001 ",
New byte [1]);
M_outputstream.flush ();
}
Catch (exception E)
{
Mylog. Warning ("an exception occurred when transferring file content from the client to the server ");
Mylog. Warning (E. getmessage ());
}
}

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.