2013-02-16 9 views
6

Sto usando InetAddress per determinare se il mio server è online.JAVA Specifica porta con InetAddress

Se il server è offline, il server verrà riavviato.

Questo processo viene ripetuto ogni 5 minuti per verificare nuovamente se il server è in linea.

Funziona bene ma ora ho bisogno di capire come specificare che voglio utilizzare la porta 43594 quando si controlla lo stato del server anziché la porta predefinita 80.

Grazie! Qui è il mio codice:

import java.net.InetAddress; 
public class Test extends Thread { 
    public static void main(String args[]) { 
     try { 
      while (true) { 
       try 
       { 
        InetAddress address = InetAddress.getByName("cloudnine1999.no-ip.org"); 
        boolean reachable = address.isReachable(10000); 
        if(reachable){ 
         System.out.println("Online"); 
        } 
        else{ 
         System.out.println("Offline: Restarting Server..."); 
         Runtime.getRuntime().exec("cmd /c start start.bat"); 
        } 
       } 
       catch (Exception e) 
       { 
        e.printStackTrace(); 
       } 
       Thread.sleep(5 * 60 * 1000); 
      } 
     } 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

EDIT:

Va bene così ho preso qualcuno consiglio e ho fatto in questo. Ma ora quando Decommentare questa linea .. Runtime.getRuntime().exec("cmd /c start start.bat");

ottengo questo errore ..

error: unreported exception IOException; must be caught or declared to be thrown

Questo è il mio codice corrente:

import java.net.*; 
import java.io.*; 
public class Test extends Thread { 
    public static void main(String args[]) { 
     try { 
      while (true) { 
       SocketAddress sockaddr = new InetSocketAddress("cloudnine1999.no-ip.org", 43594); 
       Socket socket = new Socket(); 
       boolean online = true; 
       try { 
        socket.connect(sockaddr, 10000); 
       } 
       catch (IOException IOException) { 
        online = false; 
     } 
       if(!online){ 
      System.out.println("OFFLINE: Restarting Server.."); 
      //Runtime.getRuntime().exec("cmd /c start start.bat"); 
     } 
       if(online){ 
        System.out.println("ONLINE"); 
       } 
       Thread.sleep(1 * 10000); 
      } 
     } 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

Hai provato a modificare il parametro host per includere la porta? 'cloudnine1999.no-ip.org: 43594' – Vulcan

+0

Il [Javadoc] (http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#isReachable%28int%29) dice : 'Un'implementazione tipica utilizzerà ICMP ECHO REQUEST se è possibile ottenere il privilegio, altrimenti tenterà di stabilire una connessione TCP sulla porta 7 (Echo) dell'host di destinazione. '- sei sicuro che l'implementazione che stai utilizzando stia effettivamente utilizzando un testconnection sulla porta 80? – fvu

+0

@Vulcan Grazie ma ci ho provato. – Cloudnine1999

risposta

7

Come ho già detto nei commenti , secondo il Javadoc isReachable non è implementato in un modo che consenta di controllare la porta selezionata. In realtà, se è autorizzato a farlo dai privilegi di sistema, eseguirà solo il ping della macchina (richiesta ICMP).

Farlo manualmente (ad esempio, utilizzando un socket) sarà certamente il lavoro e non è davvero più complicato e/o più a lungo:

SocketAddress sockaddr = new InetSocketAddress("cloudnine1999.no-ip.org", 43594); 
// Create your socket 
Socket socket = new Socket(); 
boolean online = true; 
// Connect with 10 s timeout 
try { 
    socket.connect(sockaddr, 10000); 
} catch (SocketTimeoutException stex) { 
    // treating timeout errors separately from other io exceptions 
    // may make sense 
    online=false; 
} catch (IOException iOException) { 
    online = false;  
} finally { 
    // As the close() operation can also throw an IOException 
    // it must caught here 
    try { 
     socket.close(); 
    } catch (IOException ex) { 
     // feel free to do something moderately useful here, eg log the event 
    } 

} 
// Now, in your initial version all kinds of exceptions were swallowed by 
// that "catch (Exception e)". You also need to handle the IOException 
// exec() could throw: 
if(!online){ 
    System.out.println("OFFLINE: Restarting Server.."); 
    try { 
     Runtime.getRuntime().exec("cmd /c start start.bat"); 
    } catch (IOException ex) { 
     System.out.println("Restarting Server FAILED due to an exception " + ex.getMessage()); 
    } 
}   

EDIT: Ho dimenticato di gestire IOException che significa anche il server non è funzionante, aggiunto

EDIT2: aggiunta la manipolazione del IOException che close() può lanciare

Edit3: e gestione delle eccezioni per exec()

+0

Grazie ha aiutato ma leggere la mia modifica. – Cloudnine1999

+0

Oh anche il socket.close() doveva essere rimosso e mi dava anche errori. – Cloudnine1999

+0

No non dovresti rimuoverlo, ho modificato il mio codice per mostrare come recuperarlo localmente. L'IMO che lancia eccezioni su operazioni close() non è la caratteristica più utile in Java, ma è così. Scusa per la confusione, il piccolo programma di test che ho usato per testare tali snippet aveva già un 'throw IOException' che mi ha fatto perdere questo problema. – fvu

Problemi correlati