2014-03-31 25 views
0

我正在使用C#,Visual Studio 2008,Framework 2.0 for embedded device。Socket連接到ftp沒有收到答案

我在使用Socket連接與FTP進行通信時遇到了問題。

在你們的目的是幫助我,我寫了一個片段來解釋我的煩惱......

 IPEndPoint endpoint; 
     Socket cmdsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 

     IPAddress address = IPAddress.Parse(args[0]); 
     endpoint = new IPEndPoint(address, int.Parse(args[1])); 

     // Connection 
     cmdsocket.Connect(endpoint); 

     if (cmdsocket.Connected) 
     { 
      do 
      { 
       Console.WriteLine("Type the command to send : "); 
       string l_sCommandToSend = Console.ReadLine(); 
       Console.WriteLine("Do you want a timeout to receive ? (Y/N (default))"); 
       string l_sReceiveTimeout = Console.ReadLine(); 

       // Sending 
       byte[] bytes = Encoding.ASCII.GetBytes((l_sCommandToSend + "\r\n").ToCharArray()); 
       cmdsocket.Send(bytes, bytes.Length, 0); 
       if (l_sReceiveTimeout == "Y") 
       { 
        Thread.Sleep(1000); 
       } 

       // Receiving 
       byte[] bufferToRead = new byte[512]; 
       string l_sResponsetext = ""; 
       int l_iByteReceivedCount = 0; 
       while (cmdsocket.Available > 0) 
       { 
        Console.WriteLine("Receiving..."); 
        l_iByteReceivedCount = cmdsocket.Receive(bufferToRead, SocketFlags.None); 
        l_sResponsetext += Encoding.ASCII.GetString(bufferToRead, 0, l_iByteReceivedCount); 
        Console.WriteLine("Bytes Received : " + l_iByteReceivedCount); 
        Console.WriteLine("l_sResponsetext : " + l_sResponsetext); 
       } 
       Console.WriteLine("This is the answer : " + l_sResponsetext); 
      } while (true); 
     } 


     Console.WriteLine("Job done."); 
     Console.ReadLine(); 

     // Fermeture du socket 
     cmdsocket.Close(); 
     cmdsocket = null; 

上面是一個片斷:

  • 連接到FTP(我在我的服務器端使用FileZilla Server進行測試)
  • 詢問用戶他想發送哪個命令
  • 詢問用戶他是否想要發送和接收之間的睡眠(更多細節l ater)
  • 閱讀並顯示答案。

我注意到如果我在FTP命令和響應之間沒有使用Sleep,有時候我沒有得到正確的響應(空字符串)。 例如,發送命令「USER Andy」將導致在沒有設置睡眠時的響應「」。當睡眠時間設置爲1秒時,我確實得到了正確的答案,即「安迪需要331密碼」。

我試圖調試我的套接字而不談論FTP並選擇了像Hercules這樣的軟件。一切都按預期工作,我的接收方法調用只是掛起,直到它收到答案。

我在這裏做錯了什麼?

回答

0

我正在寫一個FTP服務器,並在連接firt,我做的是:

streamWrite.WriteLine("220 'Any text here'"); 
streamWrite.Flush(); 

嘗試在客戶端第一次讀到。