相关数据是一个 PNG 文件,其大小为 int 前缀。
-Sending:
ns.Write(BitConverter.GetBytes((int)data.Length),0,4);
ns.Write(data, 0, data.Length);
-Reading:
byte[] sizearray = new byte[4];
ns.Read(sizearray, 0, 4);
int dataSize = BitConverter.ToInt32(sizearray,0);
byte[] data = new byte[dataSize];
ns.Read(data, 0, dataSize);
Run Code Online (Sandbox Code Playgroud)
然后将接收到的数据保存到文件中。我也用 BeginRead/EndRead 尝试过,结果相同。
问题是,虽然这适用于大多数较小的图像,但它不会收到超过几 KB 的图像。dataSize 读取正确,但每次读取几千字节后(~2900),接收到的数据的其余部分为 0。示例
我是否忽略了一些事情,比如一次可以发送多少的限制?
您忽略了 的返回值Read
。不要那样做。Read
不会等到读取您请求的所有数据。您应该循环阅读,直到读完所需的所有内容:
byte[] data = new byte[dataSize];
int index = 0;
while (index < dataSize)
{
int bytesRead = ns.Read(data, index, dataSize - index);
if (bytesRead <= 0)
{
// Or whatever exception you want
throw new InvalidDataException("Premature end of stream");
}
index += bytesRead;
}
Run Code Online (Sandbox Code Playgroud)
理论上,即使在读取时,您也需要执行相同的操作dataSize
,尽管实际上我怀疑您在一次读取中是否会收到少于 4 个字节的数据。
您可能想使用BinaryReader
环绕流 - 然后您可以使用ReadInt32
and ReadBytes
,其中ReadBytes
将为您执行循环。(您仍然需要检查返回值,但这比您自己检查更简单。)