How to Call NetworkStream.Read() Without Blocking?

14,525

Solution 1

You can use the DataAvailable property to see if there is anything to be read before making a call into the Read method.

Solution 2

Use the NetworkStream.Read() function directly, instead of using GetStream():

If no data is available for reading, the Read method returns 0. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. If the remote host shuts down the connection, and all available data has been received, the Read method completes immediately and return zero bytes. NoteNote:

Solution 3

Why do you want to empty the read buffer? If you don't want the contents of the socket close it. If you don't want the current contents, but will want later data, how do you know when later starts. If the data is an non-encapsulated stream...

Sounds like your solving the problem in the wrong fashion.

Share:
14,525
Hongseok Yoon
Author by

Hongseok Yoon

Updated on June 15, 2022

Comments

  • Hongseok Yoon
    Hongseok Yoon almost 2 years

    I'd like to empty read buffer of the socket so I wrote follow code...

    byte[] tempBuffer = new byte[1024];
    int readCount = 0;
    while ((readCount = tcpSocket.GetStream().Read(tempBuffer, 0, tempBuffer.Length)) != 0)
    {
        // do with tempBuffer
    }
    

    But Read() method is blocked so I added tcpSocket.ReceiveTimeout = 1;. And it works just like before.

    As I know, this is usually used in C++. How can I solve this problem?

  • Hongseok Yoon
    Hongseok Yoon almost 15 years
    What I meant by emptying the buffer is just I wanted to read all data from the buffer and dispatch it, not skip it. Usually I do as this way when I make server.
  • Hongseok Yoon
    Hongseok Yoon almost 15 years
    What do you mean by using the function directly? There's not that static member function. Let me see some code please.
  • Hongseok Yoon
    Hongseok Yoon almost 15 years
    I wrapped my code with try-catch block in order to detect disconnection. If I use DataAvailable property, how can I do it?
  • David Schmitt
    David Schmitt almost 15 years
    that is no static function. If you had read the MSDN link I've provided, you'd seen that this is a method on the NetworkStream object. Since you failed to provide the actual type of your tcpSocket variable I had to guess from the rest of your text.
  • Mark Heath
    Mark Heath almost 15 years
    if you follow the link to the DataAvailable method in my answer you will see that there is a code example that does what you want. You are of course free to wrap the whole thing in a try-catch to handle disconnection.
  • danyim
    danyim over 12 years
    I'm not sure what you are talking about here. The OP is actually using a NetworkStream object via tcpSocket.GetStream().