title: TcpClient still connected after server closed connection. Why?
body: <p>I have a TCP server running serving TCP clients - crazy, I know. Now I have a behavior that is not clear to me and maybe someone could help me understanding it.</p>
  
  <pre><code>[Test]
  [TestCase(2, 1)] // first scenario: Okay!
  [TestCase(1, 1)] // second scenario: Huh?
  public void NotifyClientAboutError(int clientSendBytes, int serverReadBytes)
  {
      var server = new TcpListener(IPAddress.Any, 12345);
      server.Start();
  
      Task.Factory.StartNew(() =&gt;
      {
          using (var serverClient = server.AcceptTcpClient())
          {
              using (var serverClientStream = serverClient.GetStream())
              {
                  for (var i = 0; i &lt; serverReadBytes; i++)
                  {
                      serverClientStream.ReadByte();
                  }
                  serverClientStream.Close();
              }
              serverClient.Close();
          }
      });
  
      using (var client = new TcpClient())
      {
          client.Connect(IPAddress.Loopback, 12345);
          using (var clientStream = client.GetStream())
          {
              for (var i = 0; i &lt; clientSendBytes; i++)
              {
                  clientStream.Write(new byte[] { 42 }, 0, 1);
              }
  
              // returns 0 - would have expected an Exception here
              clientStream.ReadByte();
  
              // says: true
              Console.WriteLine(client.Connected);
  
              // no exception
              clientStream.Write(new byte[] { 42 }, 0, 1);
              clientStream.Flush();
  
              // says: true
              Console.WriteLine(client.Connected);
          }
      }
  
      server.Stop();
  }
  </code></pre>
  
  <p>See the two scenarios wrapped in NUnit test cases:</p>
  
  <p><strong>First:</strong> When <em>the server reads less bytes</em> than the client sent, then closes the connection by calling <code>Close()</code> on the stream, the following call to <code>ReadByte()</code> fails with an exception. So far so good. That is what I expect.</p>
  
  <p><strong>Second:</strong> When <em>the server reads all bytes</em> sent by the client, then closes the connection, the following call to <code>ReadByte()</code> does not fail. It returns <code>0</code> and - even more strange - it states being still connected and the client can still write data on the stream without exception. </p>
  
  <p>Can someone explain why the second scenario happens like this? Or how do I manage it, to get an exception in this case?</p>