C# 如何在不阻塞的情况下调用 NetworkStream.Read()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1006119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Call NetworkStream.Read() Without Blocking?
提问by Hongseok Yoon
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.
但是 Read() 方法被阻塞了所以我添加了tcpSocket.ReceiveTimeout = 1; . 它就像以前一样工作。
As I know, this is usually used in C++. How can I solve this problem?
据我所知,这通常用于 C++。我怎么解决这个问题?
采纳答案by Mark Heath
You can use the DataAvailableproperty to see if there is anything to be read before making a call into the Read method.
在调用 Read 方法之前,您可以使用DataAvailable属性查看是否有任何要读取的内容。
回答by David Schmitt
Use the NetworkStream.Read()
function directly, instead of using GetStream()
:
NetworkStream.Read()
直接使用函数,而不是使用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:
如果没有可供读取的数据,Read 方法返回 0。Read操作读取尽可能多的数据,最多可达 size 参数指定的字节数。如果远程主机关闭连接,并且已接收到所有可用数据,则 Read 方法立即完成并返回零字节。注意注意:
回答by Simeon Pilgrim
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.
听起来您以错误的方式解决问题。