简体   繁体   中英

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?

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. You probably need to read size - 2 instead?!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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