Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top