Simple java socket client, what throws this ConnectException?

1.3k views Asked by At

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();

    }
}
1

There are 1 answers

4
nexus_2006 On

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:

nexus@Lithium ~/Desktop/Java Workspace/networking $ java ClientLesson 
java.net.ConnectException: Connection refused
Exception in thread "main" java.lang.NullPointerException
    at ClientLesson.main(ClientLesson.java:17)

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.