Windows에서 제대로 작동하는 C# 코드가 있지만 Mono Framework에서 작동하지 않습니다.Mono NetworkStream이 데이터를 읽을 수 없습니다.
저는 마지막 Mono 3.x 브랜치를 사용하고 있습니다. 나는 그것이 안정적이지는 않지만 무슨 일이 일어날 지 궁금하며, 왜 NetworkStream이 DataAvailable에서 false를 반환하는지 그리고 나는 데이터가 있다는 것을 확신한다. (Win에서 동시에 테스트 됨).
그래서 여기에는 NetworkStream에서 읽는 몇 가지 코드입니다 : 내가 성공적으로 연결 후하여 TcpClient 객체로부터는 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();
}
}
이 코드를 사용합니다.
'DataAvailable'은 * always *'false'입니까, 아니면 처음으로 루프를 통과 한 것입니까? 추신 여기서'DataAvailable' (또는'Task.Delay')은 필요 없습니다. –
예. 그것은 항상 거짓입니다. DataAvailable을 검사하지 않고 읽으면 항상 내부 예외가있는 AggregationException이 있습니다. IOException : EndRead failure. – shadeglare
Win에서 DataAvailable 검사없이 올바르게 작동합니다. – shadeglare