简体   繁体   中英

How to Call NetworkStream.Read() Without Blocking?

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?

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

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:

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.

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