我有一些C#代碼在Windows上可以正常工作,但我無法使其在Mono Framework上正常工作。Mono NetworkStream無法讀取數據
我使用的是最後一個Mono 3.x分支。我知道這並不穩定,但我很好奇會發生什麼,以及爲什麼NetworkStream一直在DataAvailable上返回false,並且我完全確信有一個數據(在Win上同時進行測試)。
因此,這裏的一些代碼從一個閱讀的NetworkStream:
public static class NetworkStreamHelper
{
/// <summary>
/// Asynchronously reads a byte array from the NetworkStream object.
/// </summary>
/// <param name="stream">The NetworkStream object to read.</param>
/// <param name="count">The byte array size to read.</param>
/// <param name="dataChunkSize">The data chunk size that used for reading chunks from the stream.</param>
/// <returns>Returns a task presents the asynchronious array read operation.</returns>
public static async Task<Byte[]> ReadBytesAsync(this NetworkStream stream, Int32 count, Int32 dataChunkSize = 512)
{
if (count <= 0)
{
throw new ArgumentException("count should not be less 1");
}
if (dataChunkSize <= 0)
{
throw new ArgumentException("dataChunkSize should not be less 1");
}
var dataChunk = new Byte[dataChunkSize];
var destination = new List<Byte>(count);
var currentBytesRead = 0;
var remainedBytesToRead = count;
var bytesToRead = 0;
var done = false;
while (!done)
{
bytesToRead = remainedBytesToRead > dataChunk.Length ? dataChunk.Length : remainedBytesToRead;
if (stream.DataAvailable)
{
currentBytesRead = await stream.ReadAsync (dataChunk, 0, bytesToRead);
}
else
{
Console.WriteLine("delay");
await Task.Delay(10);
continue;
}
if (currentBytesRead == 0)
{
continue;
}
destination.AddRange(dataChunk.Take(currentBytesRead));
remainedBytesToRead -= currentBytesRead;
done = remainedBytesToRead == 0;
}
return destination.ToArray();
}
}
我用這個代碼,當我從連接成功後的TcpClient對象中獲取的NetworkStream對象。
你的意思是'DataAvailable'是* always *'false',或者只是第一次通過循環?附:這裏不需要'DataAvailable'(或'Task.Delay')。 –
是的。這總是錯誤的。如果我讀取時沒有檢查DataAvailable,我總是得到一個帶有內部異常的AggregationException IOException:EndRead失敗。 – shadeglare
它在Win上沒有任何DataAvailable檢查時正常工作。 – shadeglare