title: TcpClient.Connected Always True
body: <p>I have a fairly simple client/server architecture using TCP client. The server is set up to close connections from clients it hasn't received a message from in two minutes. I have verified that this works fine using a C++ TCP client for my Android device. However, my C# client always appears to be connected, even after the server closes the connection. </p>
  
  <p>I've tried a variety of things and none of them seem to accurately report that the connection has been closed. TcpClient.Connected always returns true, even after sending and receiving messages, <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected.aspx" rel="nofollow">unlike what is specified in the MSDN documentation</a>. C# Client code: </p>
  
  <pre><code>var client = new TcpClient(server, port);
  var stream = client.GetStream();
  
  //Wait &gt;2 mins to get disconnected
  await Task.Delay(Timespan.FromMinutes(2.5));
  
  void Write()
  {
      try
      {
          var data = BuildByteArrayFromMyData();
          stream.Write(data , 0, data.Length);
  
          if(!client.Connected)
          {
              //Never triggered, Connected always equals true
          }
      }
  
      catch(Exception ex)
      {
          //Never triggered
      }
  }
  
  void ReadOnAnotherThread()
  {
      while (true)
      {
          try
          {
              while (!stream.DataAvailable)
              {
                  if (!client.Connected) break; //Never triggered, Connected always equals true
                  else await Task.Delay(TimeSpan.FromMilliseconds(11));
              }
  
              byte[] data = new byte[];
              int bytes = stream.Read(data, 0, data.Length);
           }
      }
  
      catch(Exception ex)
      {
          //Never triggered
      }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Q: What is the correct way to use TcpClient.Connected?</strong> </p>
  
  <hr>
  
  <p>Similar questions that do NOT answer the question proposed here: </p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/1387459/how-to-check-if-tcpclient-connection-is-closed">No accepted answer, does not address the question of why TcpClient.Connected is always true</a></li>
  </ul>
  
  <hr>