我編寫了一個需要連接到多個服務器套接字的程序。每次連接到服務器時,我嘗試將服務器的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;
}
}
請張貼完整的堆棧跟蹤。 – Kishore