2014-03-31 27 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(); 

尝试在客户端第一次读到。