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

拈花ヽ惹草 提交于 2019-12-10 10:16:47

问题


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;

回答1:


I should 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()}.




回答2:


(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.



来源:https://stackoverflow.com/questions/2607515/how-do-i-check-if-output-stream-of-a-socket-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!