如何检查套接字的输出流是否已关闭? [英] How do I check if output stream of a socket is closed?

查看:191
本文介绍了如何检查套接字的输出流是否已关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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

正如您所见,我在代码的最开头关闭套接字然后尝试使用它将一些信息发送到另一台计算机。该程序写道:以下消息已成功发送。这意味着没有抛出NullPointerException。

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.

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

已添加

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

I initialize the socket in the following way:

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


推荐答案

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

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


此类中的方法永远不会抛出I / O
异常,尽管它的一些
建设者可以。客户可以通过调用{@link
#checkError checkError()}来查询
是否有任何错误发生

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

这篇关于如何检查套接字的输出流是否已关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆