I wrote a program which needs to connect to multiple server sockets. Each time it connects to a server, I try to save the server's InetAddress and localPort as an ArrayList in an ArrayList (connectedServers
). So connectedServers
is an ArrayList of ArrayLists. Before a new connection to a server is made, I try to check whether the same server is already connected with this client by checking through connectedServers
.
While debugging in eclipse, the debugger stops at the line marked "ERROR" in the below code. In eclipse a new tab opens with the heading NumberFormatException(Throwable).<init>(String) line: 197
which shows the message Source not found
.
If I take the marked line of code outside the if
block, the connection gets made successfully. But I need it to work inside the if
block. What can be the problem? The code is as follows.
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;
}
}