2012-03-02 89 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