Don’t bother with TcpClient.Connected

The TcpClient has a Connected property that is very convenient to use but unfortunately it doesn’t do what you think it should do. A better name for this property would be WasConnected or WasLastOperationSuccessful. The problem is that this property only tells you the status of the last operation. For example, if 30 seconds ago you sent some data this property would be true. If the client that you sent data to calls Close() on their end or their network connection goes down this property will still be true. The latter case you can probably understand but the for the former case you need to understand that there’s no “connection agreement” between the two parties. When one side calls Close() its not going to stay open to send data to the other and potentially wait forever on a slow network connection. Instead, Close() just means “terminate my side”. If you want, you can roll your own handshake implementation and have the client send a ‘closing connection’ packet but neither side should assume that it will work.

For more information see MSDN:

Because the Connected property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns true. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.