How to call NetworkStream.Read () without blocking?

I would like to clear the socket read buffer so that I write the following code ...

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

But the Read () method is locked, so I added tcpSocket.ReceiveTimeout = 1; . And it works the same as before.

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

+3
source share
3 answers

You can use the DataAvailable property to see if there is anything to read before calling the Read method.

+4
source

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

, Read 0. , , . , , Read . NoteNote:

+2

Why do you want to clear the read buffer? If you do not want the contents of the socket to close it. If you do not want the current content, but want to receive later data, as you will know when it will happen later. If the data is an unencapsulated stream ...

It looks like you solved the problem incorrectly.

+1
source

Source: https://habr.com/ru/post/1710663/


All Articles