关于Java:如何检查套接字的输出流是否关闭?

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

我有以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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();
}

如您所见,我在代码的开头关闭了套接字,然后关闭了try以使用它将某些信息发送到另一台计算机。 该程序写我"以下消息已成功发送"。 这意味着未引发NullPointerException。

那么,如果Java尝试使用套接字的封闭输出流,它不会抛出异常吗? 有没有办法检查插座是关闭还是打开?

添加

我通过以下方式初始化套接字:

1
2
3
clientSideSocket = new Socket(hostname,port);
PrintWriter out = new PrintWriter(clientSideSocket.getOutputStream(), true);
browser.output = out;


我应该看起来更好。 从PrintWriter的javadoc中:

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


(a)不要在网络上使用PrintStream或PrintWriter,因为它们会抑制异常。 它们实际上仅用于日志文件或控制台,您不需要那么多。 通过网络您正在参与协议,并且您需要立即了解故障。

(b)如果关闭了它的输入或输出,则Socket.isClosed()返回true。 注意,它不会告诉您其他人是否已关闭连接-这不是其功能。 仅阅读EOS可以告诉您。