我正在使用NetworkStream.BeginRead/EndRead从套接字进行异步读取。但是,NetworkStream.EndRead()有时会返回0(即从套接字读取的0字节),我认为这表示套接字已关闭,但这不是事实,因为如果我最终调用BeginRead(),我会接收更多数据。即使在NetworkStream.EndRead返回0字节后,为什么仍然会接收数据?
这是不是一个适当的循环来连续从套接字/ NetworkStream读取数据?
void BeginContinousRead()
{
// Start the continous async read
mStream.BeginRead(mDataBuffer, 0, mDataBuffer.Length, new AsyncCallback(ProcessNetworkStreamRead), null);
}
private void ProcessNetworkStreamRead(IAsyncResult result)
{
// This will sometimes be zero?!
int bytesRead = mStream.EndRead(result);
// Continue reading more data and call this callback method again over and over, etc.
mStream.BeginRead(mDataBuffer, 0, mDataBuffer.Length, new AsyncCallback(ProcessNetworkStreamRead), null);
}
根据MSDN,我应该使用NetworkStream.DataAvailable属性,以确定是否更多的数据是可用的插座上,但是这将是FALSE,即使更多的数据可能会在晚些时候到达。
例如,根据MSDN这应该是我的回调:
private void ProcessNetworkStreamRead(IAsyncResult result)
{
// This will sometimes be zero?!
int bytesRead = mStream.EndRead(result);
while (mStream.DataAvailable)
mStream.BeginRead(mDataBuffer, 0, mDataBuffer.Length, new AsyncCallback(ProcessNetworkStreamRead), null);
}
...但因为DataAvailable为假,然后我连续读停止,从不读取任何数据,这并不正常工作。
什么是正确的异步方法来继续读取数据,直到另一端关闭套接字或我选择关闭套接字?
谢谢 - 那么正确的循环是什么?继续调用BeginRead()并让EndRead()一遍又一遍地返回0字节? – SofaKng 2012-03-21 15:24:56
我刚刚通过telneting进入我的监听套接字来测试这个,并且由于某种原因,甚至在断开我的telnet客户端之后也不会抛出异常...... – SofaKng 2012-03-21 16:01:53