title: How To Reconnect to Tcp server from tcp client upon connection failure
body: <p>I have a server, that sends some data in a very irregular periods of time and sends heartbeats for every 30 seconds of ideal time.</p>
  
  <p>I wrote a TCP client to connect to that server and read data. It works OK, however when something is wrong with the network and server becomes unavailable i need to do the following actions.</p>
  
  <p>when connection fails between client and server i need to try to reconnect to the server (repeat this process for three times with 30 seconds interval if server is not available after the interval, on successful re-connection i need to  continue working the process else i need to display message that server not available.) </p>
  
  <p>how can i achieve this? please help me. here's my code.</p>
  
  <pre><code>private void ServiceMethod(string Port, string Host)
      {
          try
          {
  
              //create a new client socket ...
              m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
              String szIPSelected = Host;
              String szPort = Port;
              int alPort = System.Convert.ToInt16(szPort, 10);
  
              System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
              System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
              //m_socClient = new Socket(remoteEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
              m_socClient.BeginConnect(remoteEndPoint, new AsyncCallback(OnClientConnect), null);
          }
          catch (SocketException se)
          {
              //Code To Handle Exception
                          }
          catch (Exception ex)
          {
  
          }
  
      }
  
      public void OnClientConnect(IAsyncResult asyn)
      {
          try
          {
              Object objData = "Client Connected";
              byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
              m_socClient.Send(byData);
              TraceService("client Connected at " + m_socClient.RemoteEndPoint);
              m_socClient.EndConnect(asyn);
  
              WaitForData(m_socClient);
          }
          catch (ObjectDisposedException)
          {
              System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
          }
          catch (SocketException se)
          {
              // MessageBox.Show(se.Message);
  
          }
  
      }
  
  
      public class CSocketPacket
      {
          public System.Net.Sockets.Socket thisSocket;
          public byte[] dataBuffer = new byte[100];
      }
  
      public void WaitForData(System.Net.Sockets.Socket soc)
      {
          try
          {
              if (pfnWorkerCallBack == null)
              {
                  pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
              }
              CSocketPacket theSocPkt = new CSocketPacket();
              theSocPkt.thisSocket = soc;
              // now start to listen for any data...
              soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
          }
          catch (SocketException se)
          {
              //MessageBox.Show(se.Message);
          }
  
      }
  
      public void OnDataReceived(IAsyncResult asyn)
      {
          try
          {
              CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
              //end receive...
              int iRx = 0;
              iRx = theSockId.thisSocket.EndReceive(asyn);
              char[] chars = new char[iRx + 1];
              System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
              int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
  
  
                      ASCIIEncoding asen = new ASCIIEncoding();
                      response = System.Convert.ToChar(System.Convert.ToUInt32("6", 16)).ToString();
                      m_socClient.Send(asen.GetBytes(response));
  
  
  
          catch (ObjectDisposedException)
          {
              System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
              if (m_socClient.Connected)
              {
                  WaitForData(m_socClient);
  
              }
  
          }
          catch (SocketException se)
          {
  
              if (m_socClient.Connected)
              {
                  WaitForData(m_socClient);
  
              }
          }
          catch (Exception e)
          {
              //MessageBox.Show(e.Message);
             if (m_socClient.Connected)
              {
                  WaitForData(m_socClient);
  
              }
          }
      }
  </code></pre>