Saturday, 7 September 2013

Simple java socket client, what throws this ConnectException?

Simple java socket client, what throws this ConnectException?

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();
}
}
Simply put: Which docs explain the connection between Socket and
ConnectException? I think ConnectException is a subtype of IOException, so
I would handle that first, then IOException after that, right?

No comments:

Post a Comment