How do you determine if a client closed their connection

Started by
1 comment, last by kuphryn 18 years ago
My server seems unable to detect if a client has closed or lost connection. My client is calling (in c#): NetworkStream.Close(); NetworkStream.Dispose(); TcpClient.Close() However, on the server side: TcpClient.Connected remains true. Also, TcpClient.GetStream() succeeds even those the stream was closed on the client side. What's the best way to determine if one of my client is gone? Thank you.
Advertisement
I may be answering my own question (unless someone knows a better way) but after lots of Googling it seems the only way to know is if a read or write to the stream fails.

So, I added this hack:

private bool IsConnected(NetworkStream stream){   try   {      Byte[] bytes = new Byte[1];      stream.Read(bytes, 0, 0);   // Read zero bytes.   }   catch   {      return false;   }   return true;}
Correct. Analyze the exceptions.

Kuphryn

This topic is closed to new replies.

Advertisement