简体   繁体   中英

Avoid NetworkStream read block

Currently I have been working on a program that receives data from the server using TcpClient. My problem is that whenever I read the stream until I can my client stops working, It just freezes. I would like to keep a continous connection to the server, but after my while function ran twice, the third loop doesn't execute read, and never returns anything.

As this answer states that I'm correct

How can I break or return this while loop, or somehow bypass the reading block?

using (NetworkStream stream = client.GetStream())
{
    byte[] data = new byte[2048];
    using (MemoryStream ms = new MemoryStream())
    {

        int numBytesRead;
        while ((numBytesRead = stream.Read(data, 0, data.Length)) > 0)
        {
            ms.Write(data, 0, numBytesRead);
        }
        return ms.ToArray();
    }
}

I will do my best to give you some hints. If you don't want the UI to be frozen, you should either put this code on a separate thread , or run it as an asynchronous task , as Wouter commented. In my opinion this would be the better approach if you neither know how many bytes you are expecting to receive, nor when they are coming to you. As you said, if you want to have this task running for a long time a thread would be a good solution.

Nevertheless, if possible, you should be concerned about two things: your TcpClient ReadTimeout property and the expected length you are passing through the third param of stream.Read() . This means that you'll be blocked for X milliseconds until you received the quantity you want. I worked a lot on transactional server, where data packages transferred between those networks came prefixed with the length of the package. If this is your case I recommend to read the prefix first, then calculate the quantity of bytes left to be read, and then perform the last read operation.

Hope this helps, this is my first answer.

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