Mono NetworkStream无法读取数据

时间:2013-06-03 17:37:47

标签: c# .net mono networkstream

我有一些C#代码可以在Windows上正常运行,但我不能使它适用于Mono Framework。

我正在使用最后一个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对象时使用此代码。

1 个答案:

答案 0 :(得分:0)

很久以前解决了。服务器断开了某些IP地址范围的连接。