How do I check if output stream of a socket is closed?

Posted by Roman on Stack Overflow See other posts from Stack Overflow or by Roman
Published on 2010-04-09T12:53:06Z Indexed on 2010/04/09 23:23 UTC
Read the original article Hit count: 443

Filed under:
|
|
|
|

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;

© Stack Overflow or respective owner

Related posts about java

Related posts about networking