title: How can I gracefully start my C# TCP client before I start my TCP server
body: <p>I am writing a fairly simple TCP/IP client application.  I am able to successfully connect when I start the server (another seperate application) and then start the client in that order.  I would like to make the client robust so that I can start it first and it doesnt break.  Also I dont want a special user action to tell the client to try and connect.  I'd also like to use non-blocking asynchronous IO on the client.  </p>
  
  <p>In order to try and accomplish this I have tried to use the Socket.BeginConnect method.  My intention is that this call will spawn a background thread which would be blocked at the EndConnect call until a connection is established.  This way my client can call this method at its startup and then continue operation. Here is my code:</p>
  
  <pre><code>public bool Init_Port(string Host)
      {
          IPHostEntry ipHostInfo = Dns.Resolve(Host);
          IPAddress ipAddress = ipHostInfo.AddressList[0];
          IPEndPoint localEndPoint = new IPEndPoint(ipAddress, PORT);
  
          try
          {
              //Create the connection
              My_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  
              My_Socket.BeginConnect(localEndPoint, new AsyncCallback(Connect_To_Port), My_Socket);
  
          }
          catch (Exception e)
          {
              ErrorHandler(e.Message);
              return false;
          }
          return true;
      }
  
      private void Connect_To_Port(IAsyncResult ar)
      {
          try
          {
              if (My_Socket != null)
              {
                  //will block the thread until a connection is made
                  My_Socket.EndConnect(ar);
  
                  Connection_Flag = true;
  
                  //Setup the asynchronous read
                  My_Socket.BeginReceive(Rx_Buffer, 0, SOCKET_BUFFER_SIZE, 0,
                                                  new AsyncCallback(Read_Port), My_Socket );
              }
          }
          catch (Exception e)
          {
              ErrorHandler(e.Message);
          }
      }
  </code></pre>
  
  <p>I test this without starting the server application.  I am hoping that the thread will be blocked at the EndConnect until my server application is started. What I observe is that EndConnect returns immediately and that I get the error message </p>
  
  <blockquote>
    <p>No connection could be made because the target machine actively refused it 127.0.0.1:50042  </p>
  </blockquote>
  
  <p>Can anyone tell me what I can do to make this asynchronous connect wait for the server application?  Thanks in advance.</p>