title: Java: Client automatically connecting to server when internet is available
body: <p>I have made a client-server application which can connect over the internet. I have hard coded in my client the server's IP which is fixed.</p>
  
  <p>My question is that I want a way that will not take a lot of processing and memory.
  I want my client to check if internet is available and then try to connect to the server if its up and running. If not then to wait and try again.
  Keeping in mind that the app is supposed to always run on your computer 24/7 and connect when possible just like skype does, in the sense that its always on and when you have the internet available and server reachable , it connects. </p>
  
  <p>My client's code that connects to the server:</p>
  
  <pre><code>private void connectToServer() throws Exception {
      showMessage("Attempting Connection... \n");
      try{
      connection = new Socket(InetAddress.getByName(serverIP), 6789);
  
      showMessage("Ok dude you are Connected to:" + connection.getInetAddress().getHostName());}
      catch(IOException e){
          int x = 0;
          while (true){
              try {
                  showMessage("Sorry Your IP was not found, \nAutomatic detection:");
                  showMessage("Now trying again");
                  connection = new Socket(InetAddress.getByName(serverIP),6789);
  
  
                  break;
              } catch (UnknownHostException e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
              } catch (IOException e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
                  showMessage("\nConnection not established, trying again\n");
              }
              /*x++;
              if(x&gt;10) break;*/
          }
          //throw new Exception();
      }
  }
  </code></pre>
  
  <p>This does work but takes a lot of processing and memory !</p>
  
  <p>I know that by adding thread.sleep(5000), I am going to add them eventually etc... 
  But this doesn't solve the memory problem. My program would be running for a long time and this doesn't stop the inevitable. </p>
  
  <p>Is there a better way?</p>
  
  <p>THANKS</p>
  
  <p>P.S : showMessage() is just my function that displays the output on my GUI</p>
  
  <p>The way I checked memory was using Window's Task Manager !
  (the memory increases drastically)</p>