2011-01-27 64 views
3

我正在使用此FtpClient庫從WinForms應用程序連接到大型機。我正在使用thread.Sleep線程在開始讀取之前等待響應,否則它會凍結。有沒有其他方法可以做到這一點?插槽讀取之前的Thread.Sleep()的替代方法

public void Login() 
{ 
    if (this.loggedin) this.Close(); 

    Debug.WriteLine("Opening connection to " + this.server, "FtpClient"); 

    IPAddress addr = null; 
    IPEndPoint ep = null; 

    try 
    { 
     this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     addr = Dns.Resolve(this.server).AddressList[0]; 
     ep = new IPEndPoint(addr, this.port); 
     this.clientSocket.Connect(ep); 
    } 
    catch (Exception ex) 
    { 
     // doubtfull 
     if (this.clientSocket != null && this.clientSocket.Connected) this.clientSocket.Close(); 

     throw new FtpException("Couldn't connect to remote server", ex); 
    } 

    **Thread.Sleep(4000);** 
    this.readResponse(); 
    ... 
} 

private void readResponse() 
{ 
    this.message = ""; 
    this.result = this.readLine(); 

    if (this.result.Length > 3) 
     this.resultCode = int.Parse(this.result.Substring(0, 3)); 
    else 
     this.result = null; 
} 

private string readLine() 
{ 
    while (true) 
    { 
     this.bytes = clientSocket.Receive(this.buffer, this.buffer.Length, 0); 
     this.message += ASCII.GetString(this.buffer, 0, this.bytes); 

     if (this.bytes < this.buffer.Length) break; 
    } 

    string[] msg = this.message.Split('\n'); 
    if (this.message.Length > 2) 
    { 
     this.message = msg[msg.Length - 2]; 
     try { response = msg[msg.Length - 3]; } 
     catch { } 
    } 
    else 
    { 
     this.message = msg[0]; 
    } 

    if (this.message.Length > 4 && !this.message.Substring(3, 1).Equals(" ")) return this.readLine(); 

    if (this.verboseDebugging) 
    { 
     for (int i = 0; i < msg.Length - 1; i++) 
     { 
      Debug.Write(msg[i], "FtpClient"); 
     } 
    } 
    return message; 
} 

public void sendCommand(String command) 
{ 
    if (this.verboseDebugging) Debug.WriteLine(command, "FtpClient"); 

    Byte[] cmdBytes = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray()); 
    clientSocket.Send(cmdBytes, cmdBytes.Length, 0); 
    this.readResponse(); 
} 

回答

4

使用異步編程模型:

socket.BeginConnect(ep, new AsyncCallback(Connected), socket); 

void Connected (IAsyncResult result) 
{ 
    var socket = (Socket)result.AsyncState; 

    // do the stuff 

    socket.EndConnect(result); 
} 
+0

它的工作用於登錄,但在發送其他命令時(上傳/下載),我收到此錯誤「在先前的異步調用正在進行時無法阻止此套接字上的調用。」。 – user558138 2011-01-28 09:21:06

+0

@ user558138:抱歉忘了說你需要調用`EndConnect()` – abatishchev 2011-01-28 09:51:10