2012-03-02 49 views
2

響應,我有以下一段代碼來聽一個端口是55000.無限循環從服務器

static void TcpEchoServer(string _servPort) 
{ 
    int servPort = Convert.ToInt32(_servPort); 

    TcpListener listener = null; 

    try 
    { 
     listener = new TcpListener(IPAddress.Any, servPort); 
     listener.Start(); 
    } 
    catch (SocketException sec) 
    { 
     Console.WriteLine(sec.ErrorCode + ": " + sec.Message); 
     Environment.Exit(sec.ErrorCode); 
    } 

    byte[] rcvBuffer = new byte[BUFSIZE]; 
    int bytesRcvd; 

    for (; ;) 
    { 
     TcpClient client = null; 
     NetworkStream netStream = null; 

     try 
     { 
      // Get client connection and stream 
      client = listener.AcceptTcpClient(); 
      netStream = client.GetStream(); 
      Console.Write("Handling client - "); 

      // Receive until client closes connection, indicated by 0 return value 
      int totalBytesEchoed = 0; 
      bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length); 

      while (bytesRcvd > 0) 
      { 
       netStream.Write(rcvBuffer, 0, bytesRcvd); 
       totalBytesEchoed += bytesRcvd; 
      } 

      Console.WriteLine("echoed {0} bytes.", totalBytesEchoed); 

      // Close stream and socket 
      netStream.Close(); 
      client.Close(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      netStream.Close(); 
     } 
    } 
} 

一旦我打開啓動服務器,我telnet我的命令提示符併發送消息,但不斷得到一個循環響應我的客戶端,但沒有響應我的服務器。任何人發現我的問題?我不能。我在Mac機器上的VMWare上開發Window 7 VS2010 C#,並從Mac終端遠程登錄。

screenshot1

[EDIT - 代碼答案]

我簡單地分配字節接收變量的while循環中,所以不會循環,只要它完成。謝謝你指出這個問題。以下是我的解決方案代碼:

while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) 
{ 
    netStream.Write(rcvBuffer, 0, bytesRcvd); 
    totalBytesEchoed += bytesRcvd; 
} 

回答

3

罪魁禍首是:

while (bytesRcvd > 0) 

只要收到任何消息,它將無限循環(您不必爲防止這樣的情況)。

這也許可以用一個簡單的if更換,除非出於某種原因(在你的代碼並不明顯),你就需要循環:

if (bytesRcvd > 0) 

在第二次看,它看起來很像你想驗證所有的字節被髮送通過使用此代碼:

while (bytesRcvd > 0) 
{ 
    netStream.Write(rcvBuffer, 0, bytesRcvd); 
    totalBytesEchoed += bytesRcvd; 
} 

第三個參數是不是一個ByRef參數,因此它不會與實際發送(如果小於值的值被更新通過)。 WriteRead略有不同,因爲如果無法傳送請求的字節數(而不是通知您有多少成功),它實際上會拋出SocketException。我可能會改變爲:

if (bytesRcvd == 0) 
    throw new SocketException(String.Format("Unable to receive message"); 

netStream.Write(rcvBuffer, 0, bytesRcvd); 
totalBytesEchoed += bytesRcvd; 

或者更好的實現一些基本的信息來取景讓您的應用程序知道它應該有多少字節的期望。

+0

+1您指出了問題。用我的解決方案查看編輯的問題我在while循環的條件中分配變量。到目前爲止它的工作。 – KMC 2012-03-03 01:01:15