2009-08-13 82 views
7

我使用以下類來測試主機是否接受來自java的連接與Java的測試套接字連接

我的問題是,這裏可以增強什麼?

感謝您的反饋

編輯

我已經加入以秒可選參數 「超時」。

import java.io.IOException; 
import java.net.Socket; 
import java.net.InetSocketAddress; 
import java.net.SocketAddress; 

public class TestConnection { 

    public static void main(String [] args) { 

     int timeout = 2000; // two seconds  

     if(isInvalidInput(args)) { 

      System.err.println("Usage: java TestConnection remotehost port [timeout_seconds]"); 
      System.exit(-1); 

     } else if (args.length == 3) try { 

      timeout = Integer.parseInt(args[2]) * 1000; 

     } catch(NumberFormatException nfe){} 

     String host = args[0]; 
     String port = args[1]; 

     System.out.printf("Attempting: %s port: %s ....\n", host, port); 

     Socket socket = new Socket(); 
     InetSocketAddress endPoint = new InetSocketAddress(host, 
               Integer.parseInt(port) ); 

     if (endPoint.isUnresolved()) { 

      System.out.println("Failure " + endPoint); 

     } else try { 

      socket.connect( endPoint , timeout); 
      System.out.printf("Success: %s \n", endPoint); 

     } catch(IOException ioe) { 

      System.out.printf("Failure: %s message: %s - %s \n", 
       endPoint , ioe.getClass().getSimpleName(), ioe.getMessage()); 

     } finally { 

      if (socket != null) try { 
       socket.close(); 
      } catch(IOException ioe) {} 

     } 

    } 

    /** 
    * Validates the number of arguments is exactly 2 and the second is a number. 
    * @return true is args.length == 2 && args[1].matches(\\d+); 
    */ 
    private static final boolean isInvalidInput(String [] args) { 
     return (args.length < 2 
        || (args.length >= 2 && !args[1].matches("\\d+"))); 
    } 

} 
+2

我愛if()try {constructs:P – OscarRyz 2009-08-13 18:42:01

+2

我不想見到你的靈魂伴侶,然後:) – mgarciaisaia 2014-02-18 20:33:31

回答

3

增強?如果你正在談論代碼的複雜性:你沒有任何循環(while,while),只有1個條件(if)。所以複雜度很難降低。

由於您在顯示參數時的用法,我假設這將由用戶使用,而不是由您自己的代碼的另一部分使用。你需要保持這一點。

如果您擔心在主機未響應時聯繫主機的時間,可以設置自己的超時時間。如果你不熟悉超時時間read this

您的代碼對於主機響應的情況是最佳的。

+0

當它需要太多的連接時,它實際上讓我感到不安。我修改了這個版本來處理可選參數「超時」現在我想知道是否使用「isUnresolved()」方法是好的。 :) – OscarRyz 2009-08-13 18:40:06

+2

小心:名稱解析意味着查看主機名是否鏈接到一個IP地址。這不是一回事。例如www.google.com可以解析爲66.102.1.147。 – 2009-08-13 19:09:54

+0

另外:「else if(args.length == 3)」是無用的,因爲系統在if中退出。並且不要離開empy catch(NumberFormatException)...這不是一個好習慣。如果用戶輸入的值不是數字,那麼您的代碼將默默恢復爲2000.沉默是好的;)但在這種情況下不會。 – 2009-08-13 19:17:34

2

該代碼非常合理。而且由於時間短,所以沒有太多的必須切斷。

如果我編碼端口掃描器,我會刪除isInvalidInput方法。相反,我會假設輸入是有效的。如果用戶輸入的內容不是有效整數,請在那裏捕獲解析錯誤並告訴他重新輸入。