title: Continuously connecting to a server via a Socket until a connection is established
body: <p>I have a client that I want to try to continuously connect to a server until a connection is established (i.e. until I start the server).</p>
  
  <pre><code>clientSocket = new Socket();
  while (!clientSocket.isConnected()) {
      try {
          clientSocket.connect(new InetSocketAddress(serverAddress, serverPort));
      } catch (IOException e) {
          e.printStackTrace();
      }
  
      // sleep prevents a billion SocketExceptions from being printed,
      // and hopefully stops the server from thinking it's getting DOS'd
      try {
          Thread.sleep(1500);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>After the first attempt, I get a <code>ConnectionException</code>; expected, since there is nothing to connect to. After that, however, I start getting <code>SocketException: Socket closed</code> which doesn't make sense to me since <code>clientSocket.isClosed()</code> always returns false, before and after the <code>connect()</code> call.</p>
  
  <p>How should I change my code to get the functionality I need?</p>