title: TcpClient communication with server to keep alive connection in c#?
body: <p>I've this TcpClient code which works fine. It connects to perl server on linux system and receives anything that server sents to it. Works nicely. </p>
  
  <pre><code> public static void Main() {
           foreach (ProtocolConnection tcpConnection in TcpConnectionsList) {
                  ProtocolConnection connection = tcpConnection;
                  ThreadPool.QueueUserWorkItem(_ =&gt; {
                                                   ThreadTcpClient(connection);
                                                   ManualResetEventTcp.Set();
                                               });
           }
           ... Some code...      
   }
  
   public static void TcpConnect(ProtocolConnection varConnection) {
          int retryCountSeconds = varConnection.RetryEverySeconds*Program.MilisecondsMultiplier;
          int count = 0;
          while (true) {
  
              try {
                  using (var client = new TcpClient(varConnection.IpAddress.ToString(), varConnection.Port) { NoDelay = true })
                  using (var stream = client.GetStream()) {
                      var data = new Byte[256];
                      while (!Program.PrepareExit) {
                          Int32 bytes = stream.Read(data, 0, data.Length);
                          string varReadData = Encoding.ASCII.GetString(data, 0, bytes).Trim();
                          if (varReadData != "" &amp;&amp; varReadData != "PONG") {
                              VerificationQueue.EnqueueData(varReadData);
                              Logging.AddToLog("[TCP][" + varConnection.Name + "][DATA ARRIVED]" + varReadData);
                          } else {
                              Logging.AddToLog("[TCP]" + varReadData);
                          }
                      }
                  }
              } catch (Exception e) {
                  if (e.ToString().Contains("No connection could be made because the target machine actively refused it")) {
                      Logging.AddToLog("[TCP][ERROR] Can't connect to server (" + varConnection.Name + ") " + varConnection.IpAddress + ":" + varConnection.Port );
                  } else {
                      Logging.AddToLog(e.ToString());
                  }
  
              }
              DateTime startTimeFunction = DateTime.Now;
              do {
                  Thread.Sleep(1000);
              } while (((DateTime.Now - startTimeFunction).TotalSeconds &lt; retryCountSeconds));
          }
      }
  </code></pre>
  
  <p>However in certain conditions I'm having some problems with it:</p>
  
  <ol>
  <li>My work connection often drops connection after some idle time so I've implemented in server so when it receives PING it responds with PONG. I can send PING with UDP to server and it will respond with PONG on tcp but i would prefer built-in way into tcp client so it does send PING every 60 seconds or so. Even if UDP solution would be acceptable I have no timeout on <code>string varReadData = Encoding.ASCII.GetString(data, 0, bytes).Trim();</code> so when PONG doesn't arrive my client doesn't even notice it anyway. It just keeps waiting ... which brings me to.. </li>
  <li>My other problem is that at some point <code>string varReadData = Encoding.ASCII.GetString(data, 0, bytes).Trim();</code> this is waiting for data all the time. When server crashes or disconnects my client i don't even notice that. I would like server to have some kind of <code>timeout</code> or check if connection is active. If it's not active it should try to reconnect. </li>
  </ol>
  
  <p>What would be simplest way to fix this TcpClient ? How do i implement both way communication making sure that if server drops my connections or my net gets disconnected client will notice it and reestablish connection ? </p>