NetworkStream.DataAvailable

  • Thread starter Thread starter Hai Ly Hoang - MT00KSTN
  • Start date Start date
H

Hai Ly Hoang - MT00KSTN

Hi,
When NetworkStream.DataAvailable flag is toogled ?
The explanation of MSDN is so vague and confusing !

Thanks
 
Hai Ly Hoang - MT00KSTN said:
Hi,
When NetworkStream.DataAvailable flag is toogled ?
The explanation of MSDN is so vague and confusing !
The DataAvailable property will be true when data is present on
the socket for reading. The Read() method will block until there is
data that can be read. If you don't want your application to block on
the Read(), you can first check the stream with the DataAvailable
property. If it returns false, you know that the Read() method would
block, and can avoid calling it.

As a side benefit, the DataAvailable property will throw an
Exception if the remote host has closed the stream. By catching that
in a try-catch block you can determine when the remote host has closed
the connection:

try {
if (ns.DataAvailable)
{
int recv = ns.Read(data, 0, data.length)
} else
{
Console.WriteLine("No data available yet");
}
} catch(SocketException)
{
Console.WriteLine("The remote host has disconnected");
ns.Close();
}

Hope this helps clear things up some.

Rich Blum - Author
"C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
"Network Performance Open Source Toolkit" (Wiley)
http://www.wiley.com/WileyCDA/WileyTitle/productCd-0471433012.html
 
Back
Top