在插座中接收未知尺寸时适合循环?

时间:2014-05-23 12:43:37

标签: java c# sockets

我目前正在研究Java< - > C#套接字通信。阅读了this之类的教程后,我注意到许多教程都有类似的循环,例如;

 while (true)
  {
    bytesRead = 0;

    try
    {
      //blocks until a client sends a message
      bytesRead = clientStream.Read(message, 0, 4096);
    }
    catch
    {
      //a socket error has occured
      break;
    }

    if (bytesRead == 0)
    {
      //the client has disconnected from the server
      break;
    }

    //message has successfully been received
    ASCIIEncoding encoder = new ASCIIEncoding();
    System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
  }

  tcpClient.Close();
}

其中message是字节数组(缓冲区)。

我常常遇到while(true)循环问题。我的理解是,因为clientStream.Read(及其在Java中的类似对应物)将它作为int读入缓冲区的字节数返回。所以我倾向于编写以下代码;

int bytesRead = clientStream.Read(message, 0, message.Length);
stringBuilder.Append(encoder.GetString(message, 0, bytesRead));
Console.WriteLine("Read: " + bytesRead);
while (bytesRead==message.Length)
{
  try
  {
    //blocks until a client sends a message
    bytesRead = clientStream.Read(message, 0, message.Length);            
  }
  catch
  {
     //a socket error has occured
     break;
  }
  if (bytesRead == 0)
  {
     //the client has disconnected from the server
     break;
  }
  else
  {
     stringBuilder.Append(encoder.GetString(message, 0, bytesRead));
  }
  Console.WriteLine("Read: " + bytesRead);
}

你会注意到我已经改变了while (bytesRead==message.Length)。我更改了循环,以便只有当我的缓冲区已满时才会进入它(因此需要读取更多数据)并将保留在循环中,直到它读取的字节数小于缓冲区可容纳的最大值

当我运行我的版本时,我似乎无法解决使用教程中找到的方法时遇到的问题。我忽略了什么吗?我的方法最终会导致任何我无法注意到的错误吗?

0 个答案:

没有答案