【发布时间】:2011-11-18 23:03:13
【问题描述】:
当服务器套接字关闭时,即使在OutputStream上写入并且服务器套接字已经关闭之后,客户端也不会收到任何异常>.
提供以下类来测试:
public class ModemServerSocket {
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket = new ServerSocket(63333);
Socket client = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
String s;
while ((s = reader.readLine()) != null) {
System.out.println(s);
if (s.equals("q")) {
break;
}
}
serverSocket.close();
}
}
公共类 ModemClientSocket {
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket = new Socket("localhost", 63333);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
String[] sArray = {"hello", "q", "still there?"};
for (String s : sArray) {
writer.println(s);
if (s.equals("q")) {
Thread.sleep(5 * 1000);
}
}
System.out.println("Whoop. No exception. The client didn't notice.");
}
}
我所做的是启动 ModemServerSocket 应用程序,然后启动 ModemClientSocket 应用程序。
ModemServerSocket 输出:
hello
q
ModemClientSocket 输出:
Whoop. No exception. The client didn't notice.
这是预期的行为吗?为什么会这样?
但是我做了另一个测试,我关闭了 ModemClientSocket 并且 ModemServerSocket 尝试从 InputStream 中读取,在这种情况下我得到了一个 java.net.SocketException 这是我所期望的。奇怪的是 PrintWriter (OutputStream) 没有发生这种情况,也没有抛出异常。
我使用 Java 1.6.0 Update 26 进行测试。
【问题讨论】: