【问题标题】:Stream.Read doesn't return received dataStream.Read 不返回接收到的数据
【发布时间】:2016-06-09 10:23:18
【问题描述】:

这是我喜欢使用的方法。我相信,这段代码没有什么新东西。

 public static byte[] ReadFully(Stream stream, int initialLength)
    {
        // If we've been passed an unhelpful initial length, just
        // use 1K.
        if (initialLength < 1)
        {
            initialLength = 1024;
        }

        byte[] buffer = new byte[initialLength];
        int read = 0;

        int chunk;
        while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
        {
            read += chunk;

            // If we've reached the end of our buffer, check to see if there's
            // any more information
            if (read == buffer.Length)
            {
                int nextByte = stream.ReadByte();

                // End of stream? If so, we're done
                if (nextByte == -1)
                {
                    return buffer;
                }

                // Nope. Resize the buffer, put in the byte we've just
                // read, and continue
                byte[] newBuffer = new byte[buffer.Length * 2];
                Array.Copy(buffer, newBuffer, buffer.Length);
                newBuffer[read] = (byte)nextByte;
                buffer = newBuffer;
                read++;
            }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
    }

我的目标是读取从 TCP 客户端发送的数据,例如box{"id":1,"aid":1} 这是在我的应用程序中以类似 Jason 的文本解释的命令。 并且此文本不一定每次都具有相同的大小。 下次可以有run{"id":1,"aid":1,"opt":1}

该行调用的方法;

var serializedMessageBytes = ReadFully(_receiveMemoryStream, 1024);

Please click to see; Received data in receiveMemoryStream 虽然我们可以看到流中的数据, 在ReadFully方法中,“chunck”总是返回0,该方法返回{byte[0]}

非常感谢任何帮助。

【问题讨论】:

  • 为什么不直接使用stream.CopyTo(memoryStream),然后使用memoryStream.ToArray()
  • 因为缓冲区?
  • 在底层,流默认缓冲区大小是DefaultCopyBufferSize = 81920;
  • 热连;感谢您的输入。你实际上是对的。
  • Jeoren 的评论可能会拯救我的一天。它返回一个字节数组,其中包含我期望的数据。但是,这个想法是使用这种方法来处理更大的数据,大小随机。然后您可以分块使用数据,以避免内存不足或任何其他 IO 问题。如果是这种情况,我仍然想在未来的扩展中使用这种方法,那么“Stream.Read”有什么问题呢?谢谢。

标签: c# stream bytearray


【解决方案1】:

在 Watch 窗口中查看您的流,流的位置 (19) 位于数据的末尾,因此没有任何内容可供读取。这可能是因为您刚刚将数据写入流并且随后没有重置位置。

如果您乐于始终从流的开头读取,请在函数的开头添加 stream.Position = 0;stream.Seek(0, System.IO.SeekOrigin.Begin); 语句,或者检查填充流的代码。请注意,一些流实现不支持搜索。

【讨论】:

  • 杰克逊,好球。一旦我将位置倒回 0,它才刚刚开始工作。事实上,在调用该方法之前对此进行了重置。 _receiveMemoryStream.Position = 0;。但是,在此重置和方法调用之间,还有其他一些使用流的调用,并且很可能它们再次将位置留在数组末尾。所以,幸福的结局。谢谢。
猜你喜欢
  • 2020-12-27
  • 2018-01-21
  • 1970-01-01
  • 2021-01-09
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
相关资源
最近更新 更多