2014-03-05 254 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

相关问题