TcpClient
我有一种通过's读取一些数据的方法,NetworkStream
它一直给我一些错误。
在调查过程中,我发现它实际上工作得很好……但前提是我使用 Visual Studio 2012 的调试器使用断点单步执行代码。
这是我的代码:
public static byte[] DownloadStream(string hostname, int port,
byte[] requestBytes, int bufferSize = 4096)
{
byte[] responseBytes = null;
var client = new System.Net.Sockets.TcpClient(hostname, port);
if (client.Connected)
{
using (var stream = client.GetStream())
{
stream.Write(requestBytes, 0, requestBytes.Length);
stream.Flush();
if (stream.CanRead)
{
var responseStream = new System.IO.MemoryStream();
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
responseStream.Write(buffer, 0, bytesRead);
}
while (stream.DataAvailable);
responseBytes = responseStream.ToArray();
}
}
}
client.Close();
return responseBytes;
}
这非常令人沮丧,因为没有真正的错误。它显然只需要调试器在读取NetworkStream
.
有谁知道为什么会这样?我该如何解决?
编辑:
出于某种原因,进行此更改可以消除问题:
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
responseStream.Write(buffer, 0, bytesRead);
System.Threading.Thread.Sleep(1); //added this line
}
while (stream.DataAvailable);
对此有何见解?