简体   繁体   中英

NetworkStream.Read not receive all data

I'm using C# to write a code for sending an image Everything works perfectly when I'm writing or reading from localhost as the IP (same PC) but when I use another PC for reading, I'm getting an error; the image sometimes is only half image, quarter of the image and sometimes nothing

This is the reading code

byte[] readBytes(int length)
{
    NetworkStream stream = client.GetStream();
    byte[] bytes = new byte[length];
    int recv=  stream.Read(bytes, 0, length);
    while (recv < length)
    {
        length -= recv;
        recv = stream.Read(bytes, recv, length);
    }
    return bytes;
}

I think my while loop is incorrect. Can someone help me with this?

Your while loop is not correct. First, the condition is wrong. Imagine that each call to Read receives just one byte (try it on a piece of paper if this is not clear). Also, if it loops more than once, Read will write to the wrong place in the buffer. That's why it works on the localhost: the connection is almost instantaneous and the first Read receives everything.

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