title: C# TcpClient "The operation is not allowed on non-connected sockets."
body: <p>My goal is to create a TcpClient that <em>stays connected</em>, allowing messages to be sent to the server, as well as having a timed monitor that sends a special message to the server during a certain idle frequency.  Haven't made it too far before getting stumped.  </p>
  
  <p>With the current code, the first message sent using a console tester app receives fine, but upon sending another an exception is thrown with the message "The operation is not allowed on non-connected sockets."</p>
  
  <p>I have tried removing the stream.Dispose() line and it will hang on stream.Read(...) during the second attempt.  I have also tried making NetworkStream stream a member of the class and set it to client.GetStream() in the constructor and it will hang on stream.Read(...) during the second attempt.</p>
  
  <pre><code>public class TcpClientTest
  {
      private TcpClient client = new TcpClient();
      private string hostName;
      private int port;
  
      public TcpClientTest(string hostName, int port)
      {
          this.hostName = hostName;
          this.port = port;
          client.Connect(hostName, port);
      }
  
  
      public byte[] SendMessage(string name, string message)
      {
          if (client == null) throw new Exception("Client connection has not been established");
  
          Person person = new Person();
          person.Name = name; person.Message = message;
  
          byte[] messageBytes = (System.Text.Encoding.Unicode.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(person)));
          const int bytesize = 1024 * 1024;
          try 
          {
              NetworkStream stream = client.GetStream();
  
              if (stream != null)
              {
                  stream.Write(messageBytes, 0, messageBytes.Length); // Write the bytes  
  
                  messageBytes = new byte[bytesize]; // Clear the message   
  
                  // Receive the stream of bytes  
                  stream.Read(messageBytes, 0, messageBytes.Length);
              }
  
  
              // Clean up  
              stream.Flush();
              stream.Dispose();
          }
          catch (Exception e) 
          {
              Console.WriteLine(e.Message);
  
          }
  
          return messageBytes; // Return response  
      }
  }
  
  // In console tester app
      static void Main(string[] args)
      {
          TcpClientTest client = new TcpClientTest("127.0.0.1", 1234);
  
          string exit = "2";
          do
          {
              if (exit == "1") client.SendMessage("TEST", "TEST");              
              Console.WriteLine("1 Send Message 2 Exit");
              exit = Console.ReadLine();
          } while (exit != "2");
  
  
      }
  </code></pre>