I'm writing a very simple client for my very simple server. Line 17 throws a ConnectException at runtime if the server isn't running, I don't know why. I have looked through the docs for Socket's constructor and getInputStream(), but neither of them throw the ConnectException. I looked at the docs for the CE, and it says "Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port)." That is exactly true, the server isn't running, but I don't know how to know this other than trial and error, why isn't it in the docs for Socket?
import java.net.*;
import java.io.*;
public class ClientLesson {
//declare vars
static Socket socket;
static BufferedReader inputReader;
public static void main(String[] args) throws IOException {
try {
socket = new Socket("Lithium", 55555);
} catch (IOException ioe) {
System.out.println(ioe.toString());
}
try {
this is the problem --> inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException ioe) {
System.out.print("couldn't get I/O stream");
ioe.printStackTrace();
}
String fromServer;
while ((fromServer = inputReader.readLine()) != null) {
System.out.println(fromServer);
}
inputReader.close();
socket.close();
}
}
I just realized the problem is entirely different...the ConnectException is thrown by the Socket constructor, and handled as an IOException, since CE is a subtype, that makes sense to me now. I'm getting a NPE at line 17, but I was confused by the terminal output, here it is:
I didn't understand those two were separate issues. Now I know the problem is line 17 should check to see if the first try was successful before calling methods on the socket.