2014-03-05 251 views
0

我編寫了一個需要連接到多個服務器套接字的程序。每次連接到服務器時,我嘗試將服務器的InetAddress和localPort作爲ArrayList保存在ArrayList(connectedServers)中。所以connectedServers是ArrayList的ArrayList。在建立與服務器的新連接之前,我通過檢查connectedServers來嘗試檢查相同的服務器是否已與該客戶端連接。嘗試連接套接字時發生NumberFormatException(Throwable)錯誤

在eclipse中調試時,調試器停在下面代碼中標記爲「ERROR」的行處。在eclipse中打開一個新選項卡,標題爲NumberFormatException(Throwable).<init>(String) line: 197,其中顯示消息Source not found

如果我在if塊以外的代碼行標記,連接成功。但我需要它在if區塊內工作。可能是什麼問題?代碼如下。

public static ArrayList<ArrayList<Object>> connectedServers = new ArrayList<ArrayList<Object>>(); 

public static void main (String args[]) throws IOException { 
    listeningPort = 1111; 
    String host = takeInput("Host"); 
    int port = takeInputInt("Port"); 

    Socket a = connectToServer(host, port); 

    if (a != null) { 
     //.... 
      } 
    //.... 
} 

public static String takeInput(String inputName) throws IOException { 
    System.out.print(inputName+": "); 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    String input = br.readLine(); 
    return input; 
} 

public static int takeInputInt(String inputName) throws IOException { 
    System.out.print(inputName+": "); 
    Scanner inputInt = new Scanner(System.in); 
    int input = inputInt.nextInt(); 
    return input; 
} 

public static Socket connectToServer(String host, int port) throws IOException { 
    ArrayList<Object> element = new ArrayList<>(); 
    element.add(host); 
    element.add(port); 

    //println(connectedServers); 
    //println(element); 
    //println(connectedServers); 


    if (connectedServers.contains(element) != true) { 
     //println(host + " " + port); 
     Socket fellowServer = new Socket(host, port);//<-------ERROR!! 
     connectedServers.add(element); 
     element.remove(host); 
     element.remove(0); 
     return fellowServer; 
    } 
    else{ 
     return null; 
    } 
} 
+0

請張貼完整的堆棧跟蹤。 – Kishore

回答

0

東西可以在這裏是錯誤的輸入

Scanner inputInt = new Scanner(System.in); 
int input = inputInt.nextInt(); 
+0

如果是這種情況,那麼在'if'塊之外採用標記的代碼行將不會導致連接成功。另外,我嘗試用'BufferedInput'輸入輸入,然後使用'Integer.parseInt()'輸入端口號。得到了同樣的錯誤... – 1xQ

+1

嘗試把它嘗試繞過它來調試它,我認爲它是來自該聲明 –

+0

你是對的。它給出了一個'FileNotFoundException'。可以做些什麼來糾正這一點? – 1xQ

相關問題