我有这个代码:
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。
那么,如果 Java 尝试使用套接字的封闭输出流,它是否不会抛出异常?有没有办法检查套接字是关闭还是打开?
已添加
我按以下方式初始化套接字:
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()}.
关于java - 如何检查套接字的输出流是否关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2607515/