Why am I still getting data even after NetworkStream.EndRead returns 0 bytes?

I am using NetworkStream.BeginRead / EndRead for asynchronous reads from socket.

However, NetworkStream.EndRead () sometimes returns 0 (i.e. 0 bytes were read from the socket) which I thought indicated that the socket was closed, but it is not, because if I keep calling BeginRead () in the end I get more data.

Is this not the correct loop to continuously read data from a socket / 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);
}

      

According to MSDN, I have to use the NetworkStream.DataAvailable property to determine if more data is available on the socket, but this will be FALSE even if more data might come in later.

For example, according to MSDN, this should be my callback:

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);
}

      

... but it doesn't work as expected because DataAvailable becomes FALSE and then my continuous reads stop and no longer read data.

What is the correct asynchronous approach to continue reading data until the other end closes the socket, or I don't want to close the socket?

+3


source to share


1 answer


Instead of checking the bytesRead or DataAvailable property to check if the socket is closed, wrap the BeginRead call and catch an IOException. Then you should be told if the socket is closed.



0


source







All Articles