简体   繁体   English

C#NetworkStream.Read读取的内容比指定的多

[英]C# NetworkStream.Read reads more than specified

40-50 on the package, the program reads 2 - 4 bytes greater than the specified (temp), what could be wrong? 在包装上40-50,程序读取比指定的(温度)大2-4个字节,这可能是什么错误?

size =  nsgsout.Read(buf, 0, 2);

while (size != 2)
{
  size += nsgsout.Read(buf, size, 2 - size);
}

temp = (buf[0] + buf[1] * 256);
size = nsgsout.Read(buf, 2, temp - 2);

while (size != temp - 2)
{
    size += nsgsout.Read(buf, size + 2, temp - size + 2);
}  

I don't think this does what you think it does: 我认为这并没有您认为的那样:

temp - size+2

I suspect you expect it to mean: 我怀疑您期望它的意思是:

temp - (size + 2)

But it's really equivalent to 但这实际上相当于

(temp - size) + 2

I suspect you really want the call to be: 我怀疑您真的希望电话是:

size += nsgsout.Read(buf, size + 2, temp - size - 2);

Also note that you can change this: 另请注意,您可以更改此设置:

size = nsgsout.Read(buf, 2, temp - 2);

to just 只是

size = 0;

and just go into the loop and let that the first read too... 然后进入循环,让第一个也阅读...

2-size can be a negative number. 2尺寸可以是负数。 You probably need to read size - 2 instead?! 您可能需要阅读尺码-改为2?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM