title: Tcp connection Keep alive
body: <p>i am creating a client server application. the server is already design and in place waiting for connection from the client. Now in the client section i would like to keep the connection alive throughout th life of the application and the connection only closes when the main client application close's or shutdown  or the server closes it.</p>
  
  <p>Currently every 10 seconds Server closes the TCP connection.I tried with </p>
  
  <pre><code>socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
  </code></pre>
  
  <p>but it doesn't work for me..
  Below is my code block </p>
  
  <pre><code>public TCPStreamDevice(string RemoteIPAddress, int RemotePort, string SourceIPAddress, int SourcePortNo)        
  {
      mIpAddress = RemoteIPAddress;
      mPort = RemotePort;
  
      mClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      System.Net.IPEndPoint LocalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(SourceIPAddress), SourcePortNo);
  
      mClient.Bind(LocalEndPoint);
  
      mDataReceivedCallback = new AsyncCallback(DataReceivedTCPCallback_Handler);
      mBuffer = new byte[1024];
      Description = new DeviceDescription();
  }
  </code></pre>
  
  <p>and in the handler I have:</p>
  
  <pre><code>private void DataReceivedTCPCallback_Handler(IAsyncResult ar)
  {
      try
      {
          Socket client = (Socket)ar.AsyncState;
          int bytesReceived = client.EndReceive(ar);
  
          if (bytesReceived &gt; 0)
          {
              //to know transport level errors
              //EngineInterface.reponseReceived(mBuffer, false);
  
              ReceiveCallBackFunc(mBuffer, bytesReceived);
  
              client.BeginReceive(mBuffer, 0, 1024, SocketFlags.None, DataReceivedTCPCallback_Handler, client);
          }
          else
          {
              //disconnect
              /* when there is no datapacket  means no TCP connection is alive now (how can i keep Tcp alive here) */
          }
      }
  }
  </code></pre>