Solved long ago. A server broke connections from some ip address range.
Mono NetworkStream can't read data
-
30-05-2022 - |
Question
I've got some C# code that works fine on Windows but I can't make it works on Mono Framework.
I'm using the last Mono 3.x branch. I know it's not stable but I'm curious what could happen and why a NetworkStream alway returns false on DataAvailable and I'm completely sure that there's a data (tested at the same moment on Win).
So here's some code for reading from a 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();
}
}
I use this code when I get a NetworkStream object from a TcpClient object after successful connection.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow