我编写了一个需要连接到多个服务器套接字的程序。每次连接到服务器时,我尝试将服务器的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