views:

300

answers:

2

I have this code:

public void post(String message) {
    output.close();
    final String mess = message;
    (new Thread() {
        public void run() {
            while (true) {
                try {
                    output.println(mess);
                    System.out.println("The following message was successfully sent:");
                    System.out.println(mess);
                    break;
                } catch (NullPointerException e) {
                    try {Thread.sleep(1000);} catch (InterruptedException ie) {}
                }
            }
        }
    }).start();
}

As you can see I close the socket in the very beginning of the code and then try to use it to send some information to another computer. The program writes me "The following message was successfully sent". It means that the NullPointerException was not thrown.

So, does Java throw no exception if it tries to use a closed output stream of a socket? Is there a way to check if a socket is closed or opened?

ADDED

I initialize the socket in the following way:

clientSideSocket = new Socket(hostname,port);
PrintWriter out = new PrintWriter(clientSideSocket.getOutputStream(), true);
browser.output = out;
+6  A: 

I shuld have looked better. From the javadoc of PrintWriter:

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking {@link #checkError checkError()}.

Andrea Polci
+3  A: 

(a) Don't use PrintStream or PrintWriter over the network, as they suppress exceptions. They are really only for log files, or the console, where you don't care all that much. Over a network you are engaging in a protocol and you need to know about failures straight away.

(b) Socket.isClosed() returns true if you've closed either its input or its output. NB it doesn't tell you whether the other guy has closed the connection - that's not its function. Only reading an EOS can tell you that.

EJP