«

»

4 月
13

About how coming true FTP uploads or download brin





無標題文件

Web Design-About how coming true FTP uploads or download brings the implementation method of plan and rate-Website Design


Web Design Company

What need a specification here is, this kind has improvement through other code.

Above all our need definition is entrusted, with the gross that the document delivers in realize transmission process, the byte number that already finished and speed, convenient client end is called on the interface.

Public Delegate Void TransferProcess(long Total, long Finished, double Speed);

Call code not citing

Next we build a FTPClient kind, this kinds are based on Socket and FTP agreement to realize join FTP service, build list, upload a file, download the main method such as the file. The structure is as follows:

  

Those who need an attention is, we need to decide this incident of an incident Event TransferProcess OnTransferProcess; to need to call after example changes FTPClient, this incident is right implement plan with rate it is very important. To achieve rate we still need to define an open member StartTime(to begin time) . We are main now be to look how to upload.

/ / /

/ / / upload a file

/ / /

/ / / name of this locality file

Public Void Put(string StrFileName)

{

/ / join server

If (! BConnected)

{

Connect();

}

UpdateStatus = True;

/ / establish Socket link

Socket SocketData = CreateDataSocket();

/ / to FTP server happening memory commands

SendCommand(“STOR ” + Path.GetFileName(strFileName));

/ / how what we do not need the information that the server returns, cast piece unusual

If (! (IReplyCode==125 | | IReplyCode==150) )

{

Throw New IOException(strReply.Substring(4));

}

/ / the data that builds this locality file flows

FileStream Input = New

FileStream(strFileName, fileMode.Open);

Int IBytes = 0;

This member of Long Total = Input.Length;// basically records the total byte number of the file, use here long whole model, it is to break through the limitation of the document that can transmit 2G to control only

This member of Long Finished = 0;// basically records the byte that already finished via transmitting to count, use here long whole model, it is to break through the limitation of the document that can transmit 2G to control only

Double Speed = 0;// records transmission rate

While ((iBytes = Input.Read(buffer, 0, buffer.Length) )>0)// flows from this locality data circularly in read access to occupy buffer

{

/ / Console.WriteLine(startTime.ToString());

SocketData.Send(buffer, IBytes, 0);// transmits the data of buffer FTP server

DateTime EndTime = DateTime.Now;// sends the end time of data every time

Computation of TimeSpan Ts = EndTime – StartTime;// sends the time-interval of data every time

The byte that computation of Finished += IBytes;// finishs is counted.

Console.WriteLine(ts.Milliseconds);

/ / computational rate, noticing Finished is byte, so need conversion develops K byte

If (ts.Milliseconds>0)

{

Speed = (double)(finished / Ts.TotalMilliseconds);

Speed = Math.Round(speed * 1000 / 1024, 2);

}

/ / here is indispensable, otherwise you cannot implement plan

/ / if transmit plan incident,be changed by example, and from this locality data access is being read to occupy in flowing is not the empty byte that finishs number also is not empty word, come true entrust.

If (OnTransferProcess! = Null&&iBytes>0&&finished>0)

{

OnTransferProcess(total, finished, speed);

}

}

UpdateStatus = False;

Finished = 0;

Input.Close();// should be transmitted after finishing, need shuts data to flow, so that be visited next time.

If (socketData.Connected)

{

SocketData.Close();// shuts current Socket

}

If (! (IReplyCode==226 | | IReplyCode==250) )

{

ReadReply();

If (! (IReplyCode==226 | | IReplyCode==250) )

{

UpdateStatus = False;

Throw New IOException(strReply.Substring(4));

}

}

}

The annotate in code is written more in detail above, here explained one by one no longer, about plan implementing in download can consult with the problem of rate above code undertakes modification.

Whole code is as follows:

Using System;

Using System.net;

Using System.IO;

Using System.Text;

Using System.net.Sockets;

Namespace MMSEncoder

{

Public Delegate Void TransferProcess(long Total, long Finished, double Speed);

/ / /

/ / / FTP Client

/ / /

Public Class FTPClient

{

Public Event TransferProcess OnTransferProcess;

Public Bool UpdateStatus = True;

Public DateTime StartTime;

Private Bool IsAbortConnect = False;

#region tectonic function

/ / /

/ / / default construction function

/ / /

Public FTPClient()

{

StrRemoteHost = “” ;

StrRemotePath = “” ;

StrRemoteUser = “” ;

StrRemotePass = “” ;

StrRemotePort = 21;

BConnected = False;

}

/ / /

/ / / tectonic function

/ / /

/ / / address of FTP server IP

/ / / current server catalog

/ / / date of entry user Zhang

/ / / entry user code

/ / / FTP server port

Public FTPClient(string RemoteHost, string RemotePath, string RemoteUser, string RemotePass, int RemotePort)

{

StrRemoteHost = RemoteHost;

StrRemotePath = RemotePath;

StrRemoteUser = RemoteUser;

StrRemotePass = RemotePass;

StrRemotePort = RemotePort;

Connect();

}

#endregion

#region lands field, attribute

/ / /

/ / / address of FTP server IP

/ / /

Private String StrRemoteHost;

Public String RemoteHost

{

Get

{

Return StrRemoteHost;

}

Set

{

StrRemoteHost = Value;

}

}

/ / /

/ / / FTP server port

/ / /

Private Int StrRemotePort;

Public Int RemotePort

{

Get

{

Return StrRemotePort;

}

Set

{

StrRemotePort = Value;

}

}

/ / /

/ / / current server catalog

/ / /

Private String StrRemotePath;

Public String RemotePath

{

Get

{

Return StrRemotePath;

}

Set

{

StrRemotePath = Value;

}

}

/ / /

/ / / date of entry user Zhang

/ / /

Private String StrRemoteUser;

Public String RemoteUser

{

Set

{

StrRemoteUser = Value;

}

}

/ / /

/ / / the user logs onto a password

/ / /

Private String StrRemotePass;

Public String RemotePass

{

Set

{

StrRemotePass = Value;

}

}

/ / /

/ / / whether to login

/ / /

Private Boolean BConnected;

Public Bool Connected

{

Get

{

Return BConnected;

}

}

#endregion

#region link

/ / /

/ / / establish link

/ / /

Public Void Connect()

{

/ / user of If (IsAbortConnect) Throw New IOException(” stopped FTP” ); compulsively

SocketControl = New Socket(AddressFamily.InterNetwork, socketType.Stream, protocolType.Tcp);

IPEndPoint Ep = New IPEndPoint(IPAddress.Parse(RemoteHost) , strRemotePort);

/ / link

Try

{

SocketControl.Connect(ep);

}

Catch (Exception)

{

Throw New IOException(” cannot receive long-range server repeatedly! “) ;

}

/ / get respondent stack

ReadReply();

If (iReplyCode! = 220)

{

DisConnect();

Throw New IOException(strReply.Substring(4));

}

/ / land

SendCommand(“USER ” + StrRemoteUser);

If (! (IReplyCode==331 | | IReplyCode==230) )

{

CloseSocketConnect();// closes link

Throw New IOException(strReply.Substring(4));

}

If (iReplyCode! = 230)

{

SendCommand(“PASS ” + StrRemotePass);

If (! (IReplyCode==230 | | IReplyCode==202) )

{

CloseSocketConnect();// closes link

Throw New IOException(strReply.Substring(4));

}

}

BConnected = True;

/ / switch arrives initiative catalog

If (! String.IsNullOrEmpty(strRemotePath) )

{

ChDir(strRemotePath);

}

}

/ / /

/ / / close link

/ / /

Public Void DisConnect()

{

If (socketControl! = Null)

{

SendCommand(“QUIT” );

}

CloseSocketConnect();

}

Public Void AbortConnect()

{

If (socketControl! = Null)

{

SendCommand(“ABOR” );

}

IsAbortConnect = True;

/ / CloseSocketConnect();

}

#endregion

#region transmits mode

/ / /

/ / / transmission mode:   judges type of SCII of noise lowing 

/ / /

Public Enum TransferType {Binary, ASCII};

/ / /

/ / / the setting transmits mode

/ / /

/ / / transmission mode

Public Void SetTransferType(TransferType TtType)

{

If (ttType==TransferType.Binary)

{

Type of SendCommand(“TYPE I” );//binary is transmitted

}

Else

{

Type of SendCommand(“TYPE A” );//ASCII is transmitted

}

If (iReplyCode! = 200)

{

Throw New IOException(strReply.Substring(4));

}

Else

{

TrType = TtType;

}

}

/ / /

/ / / obtain transmission mode

/ / /

/ / / transmission mode

Public TransferType GetTransferType()

{

Return TrType;

}

#endregion

#region file is operated

/ / /

/ / / obtain file list

/ / /

/ / / of file name match string

/ / /

Public String[] Dir(string StrMask)

{

/ / establish a link

If (! BConnected)

{

Connect();

}

/ / build Socket of travel data connective

Socket SocketData = CreateDataSocket();

/ / deferent command

SendCommand(“NLST ” + StrMask);

/ / analyse respondent code

If (! (IReplyCode==150 | | IReplyCode==125 | | IReplyCode==226) )

{

Throw New IOException(strReply.Substring(4));

}

/ / achieve a result

StrMsg = “” ;

While (true)

{

Int IBytes = SocketData.Receive(buffer, buffer.Length, 0);

StrMsg += GB2312.GetString(buffer, 0, IBytes);

If (iBytes<Buffer.Length)

{

Break;

}

}

Char[] Seperator = {‘\n’ };

String[] StrsFileList = StrMsg.Split(seperator);

When SocketData.Close();// data Socket is shut, also can have return a code

If (iReplyCode! = 226)

{

ReadReply();

If (iReplyCode! = 226)

{

Throw New IOException(strReply.Substring(4));

}

}

Return StrsFileList;

}

/ / /

/ / / get file bulk

/ / /

/ / / file name

/ / / file size

Public Long GetFileSize(string StrFileName)

{

If (! BConnected)

{

Connect();

}

SendCommand(“SIZE ” + Path.GetFileName(strFileName));

Long LSize = 0;

If (iReplyCode==213)

{

LSize = Int64.Parse(strReply.Substring(4));

}

Else

{

Throw New IOException(strReply.Substring(4));

}

Return LSize;

}

/ / /

/ / / delete

/ / /

/ / / wait for delete file name

Public Void Delete(string StrFileName)

{

If (! BConnected)

{

Connect();

}

SendCommand(“DELE ” + StrFileName);

If (iReplyCode! = 250)

{

Throw New IOException(strReply.Substring(4));

}

}

/ / /

/ / / name again (if new document name and already the file weighs a name, will enclothe already had a file)

/ / /

/ / / old file name

/ / / new document name

Public Void Rename(string StrOldFileName, string StrNewFileName)

{

If (! BConnected)

{

Connect();

}

SendCommand(“RNFR ” + StrOldFileName);

If (iReplyCode! = 350)

{

Throw New IOException(strReply.Substring(4));

}

/ / if new document name and original document weigh a name, will enclothe original document

SendCommand(“RNTO ” + StrNewFileName);

If (iReplyCode! = 250)

{

Throw New IOException(strReply.Substring(4));

}

}

#endregion

#region uploads and download

/ / /

/ / / download a batch of files

/ / /

/ / / of file name match string

/ / / this locality catalog (must not end with \ )

Public Void Get(string StrFileNameMask, string StrFolder)

{

If (! BConnected)

{

Connect();

}

String[] StrFiles = Dir(strFileNameMask);

Foreach (string StrFile In StrFiles)

{

If (! StrFile.Equals(“” ))// generally speaking the last element of StrFiles may be empty string

{

If (strFile.LastIndexOf(” . If (strFile.LastIndexOf(” .. If (strFile.LastIndexOf(” … >- 1)

{

Get(strFile.Replace(“\r” , “” ) , strFolder, strFile.Replace(“\r” , “” ));

}

}

}

}

/ / /

/ / / download a file

/ / /

/ / / the file name that wants download

/ / / this locality catalog (must not end with \ )

/ / / the file name when protecting existence this locality

Public Void Get(string StrRemoteFileName, string StrFolder, string StrLocalFileName)

{

If (! BConnected)

{

Connect();

}

SetTransferType(TransferType.Binary);

If (strLocalFileName.Equals(“” ) )

{

StrLocalFileName = StrRemoteFileName;

}

If (! File.Exists(strLocalFileName) )

{

Stream St = File.Create(strLocalFileName);

St.Close();

}

FileStream Output = New

FileStream(strFolder + “\\” + StrLocalFileName, fileMode.Create);

Socket SocketData = CreateDataSocket();

SendCommand(“RETR ” + StrRemoteFileName);

If (! (IReplyCode==150 | | IReplyCode==125

| | IReplyCode==226 | | IReplyCode==250) )

{

Throw New IOException(strReply.Substring(4));

}

While (true)

{

Int IBytes = SocketData.Receive(buffer, buffer.Length, 0);

Output.Write(buffer, 0, IBytes);

If (iBytes <= 0)

{

Break;

}

}

Output.Close();

If (socketData.Connected)

{

SocketData.Close();

}

If (! (IReplyCode==226 | | IReplyCode==250) )

{

ReadReply();

If (! (IReplyCode==226 | | IReplyCode==250) )

{

Throw New IOException(strReply.Substring(4));

}

}

}

/ / /

/ / / upload a batch of files

/ / /

/ / / this locality catalog (must not end with \ )

/ / / does file name match character (can you include * and? / / / does file name match character (can you include * and??

Public Void Put(string StrFolder, string StrFileNameMask)

{

String[] StrFiles = Directory.GetFiles(strFolder, strFileNameMask);

Foreach (string StrFile In StrFiles)

{

/ / StrFile is complete file name (include method)

Put(strFile);

}

}

/ / /

/ / / upload a file

/ / /

/ / / name of this locality file

Public Void Put(string StrFileName)

{

If (! BConnected)

{

Connect();

}

UpdateStatus = True;

Socket SocketData = CreateDataSocket();

SendCommand(“STOR ” + Path.GetFileName(strFileName));

If (! (IReplyCode==125 | | IReplyCode==150) )

{

Throw New IOException(strReply.Substring(4));

}

FileStream Input = New

FileStream(strFileName, fileMode.Open);

Int IBytes = 0;

Long Total = Input.Length;

Long Finished = 0;

/ / DateTime StartTime = DateTime.Now;

Double Speed = 0;

While ((iBytes = Input.Read(buffer, 0, buffer.Length) )>0)

{

Console.WriteLine(startTime.ToString());

SocketData.Send(buffer, IBytes, 0);

DateTime EndTime = DateTime.Now;

TimeSpan Ts = EndTime – StartTime;

Finished += IBytes;

Console.WriteLine(ts.Milliseconds);

If (ts.Milliseconds>0)

{

Speed = (double)(finished / Ts.TotalMilliseconds);

Speed = Math.Round(speed * 1000 / 1024, 2);

}

If (OnTransferProcess! = Null&&iBytes>0&&finished>0)

{

OnTransferProcess(total, finished, speed);

}

}

UpdateStatus = False;

Finished = 0;

Input.Close();

If (socketData.Connected)

{

SocketData.Close();

}

If (! (IReplyCode==226 | | IReplyCode==250) )

{

ReadReply();

If (! (IReplyCode==226 | | IReplyCode==250) )

{

UpdateStatus = False;

Throw New IOException(strReply.Substring(4));

}

}

}

#endregion

#region catalog is operated

/ / /

/ / / found catalog

/ / /

/ / / catalog name

Public Void MkDir(string StrDirName)

{

If (! BConnected)

{

Connect();

}

SendCommand(“MKD ” + StrDirName);

If (iReplyCode! = 257)

{

Throw New IOException(strReply.Substring(4));

}

}

/ / /

/ / / delete catalog

/ / /

/ / / catalog name

Public Void RmDir(string StrDirName)

{

If (! BConnected)

{

Connect();

}

SendCommand(“RMD ” + StrDirName);

If (iReplyCode! = 250)

{

Throw New IOException(strReply.Substring(4));

}

}

/ / /

/ / / change catalog

/ / /

/ / / new working catalog name

Public Void ChDir(string StrDirName)

{

If (strDirName.Equals(” . If (strDirName.Equals(” .. ) | | StrDirName.Equals(“” ) )

{

Return;

}

If (! BConnected)

{

Connect();

}

SendCommand(“CWD ” + StrDirName);

If (iReplyCode! = 250)

{

Throw New IOException(strReply.Substring(4));

}

This.strRemotePath = StrDirName;

}

#endregion

#region interior is variable

/ / /

/ / / the respondent information that the server returns (include respondent code)

/ / /

Private String StrMsg;

/ / /

/ / / the respondent information that the server returns (include respondent code)

/ / /

Private String StrReply;

/ / /

/ / / the respondent code that the server returns

/ / /

Private Int IReplyCode;

/ / /

/ / / undertake controlling connective Socket

/ / /

Private Socket SocketControl;

/ / /

/ / / transmission mode

/ / /

Private TransferType TrType;

/ / /

/ / / the buffer that receive and transmits data

/ / /

Private Static Int BLOCK_SIZE = Int16.MaxValue;

Byte[] Buffer = New Byte[BLOCK_SIZE];

/ / /

/ / / encode means (to prevent occurrence Chinese chaos the code uses GB2312 encode means)

/ / /

Encoding GB2312 = Encoding.Default;//Encoding.GetEncoding(“gb2312” );

#endregion

#region in-house function

/ / /

/ / / group respondent string record is mixed in StrReply StrMsg

/ / / respondent code record is in IReplyCode

/ / /

Private Void ReadReply()

{

StrMsg = “” ;

StrReply = ReadLine();

IReplyCode = Int32.Parse(strReply.Substring(0, 3));

}

/ / /

/ / / build Socket of travel data connective

/ / /

/ / / data join Socket

Private Socket CreateDataSocket()

{

SendCommand(“PASV” );

If (iReplyCode! = 227)

{

Throw New IOException(strReply.Substring(4));

}

Int Index1 = StrReply.IndexOf(‘(‘);

Int Index2 = StrReply.IndexOf(‘)’);

String IpData =

StrReply.Substring(index1 + 1, index2 – Index1 – 1);

Int[] Parts = New Int[6];

Int Len = IpData.Length;

Int PartCount = 0;

String Buf = “” ;

For (int I = 0; I<Len &&PartCount <= 6; I++ )

{

Char Ch = Char.Parse(ipData.Substring(i, 1));

If (Char.IsDigit(ch) )

Buf += Ch;

Else If (ch! = ‘ , ‘ )

{

Throw New IOException(“Malformed PASV StrReply: “+

StrReply);

}

If (ch==’ , ‘ | | I + 1==Len)

{

Try

{

Parts[partCount++] = Int32.Parse(buf);

Buf = “” ;

}

Catch (Exception)

{

Throw New IOException(“Malformed PASV StrReply: “+

StrReply);

}

}

}

String IpAddress = Parts[0] + ” . String IpAddress = Parts[0] + ” .. + Parts[1] + ” . + Parts[1] + ” .. +

Parts[2] + ” . Parts[2] + ” .. + Parts[3];

Int Port = (parts[4] <<8) + Parts[5];

Socket S = New

Socket(AddressFamily.InterNetwork, socketType.Stream, protocolType.Tcp);

IPEndPoint Ep = New

IPEndPoint(IPAddress.Parse(ipAddress) , port);

Try

{

S.Connect(ep);

}

Catch (Exception)

{

Throw New IOException(” cannot join server ” );

}

Return S;

}

/ / /

/ / / shut Socket to join (with Yu Denglu previously)

/ / /

Private Void CloseSocketConnect()

{

If (socketControl! = Null)

{

SocketControl.Close();

SocketControl = Null;

}

BConnected = False;

}

/ / /

/ / / read all string that take Socket to return

/ / /

/ / / the string that includes respondent code goes

Private String ReadLine()

{

While (true)

{

Int IBytes = SocketControl.Receive(buffer, buffer.Length, 0);

StrMsg += GB2312.GetString(buffer, 0, IBytes);

If (iBytes<Buffer.Length)

{

Break;

}

}

Char[] Seperator = {‘\n’ };

String[] Mess = StrMsg.Split(seperator);

If (strMsg.Length>2)

{

StrMsg = Mess[mess.Length – 2];

/ / Seperator[0] is 10, line feed accord with is by 13 with 0 composition, after space 10 from the back although do not have string,

/ / but also can allocate give for empty string from the back (also be the last) string array,

/ / so the last Mess is trashy empty string

/ / but why to take Mess[0] directly, because have last string only,case is free between respondent code and information

}

Else

{

StrMsg = Mess[0];

}

If (! StrMsg.Substring(3, 1).Equals(” ” ))// returns string correct is with respondent code (like 220 begin, one blank space is received from the back, receive complimentary string again)

{

Return ReadLine();

}

Return StrMsg;

}

/ / /

/ / / send an order and get respondent code and last respondent string

/ / /

/ / / command

Private Void SendCommand(String StrCommand)

{

Byte[] CmdBytes =

GB2312.GetBytes((strCommand + “\r\n” ).ToCharArray());

SocketControl.Send(cmdBytes, cmdBytes.Length, 0);

ReadReply();

}

#endregion

}

}

Web Hosting