我无法在任何地方找到这个问题的令人满意的答案。了解内部原理的人可以解释一下吗?
我写了一个简单的客户端/服务器来演示这个问题。 服务器读取一行文本然后关闭套接字。客户端写入一行文本,等待 10 秒,然后再写入两行文本。第二次写入(10 秒后)失败,但第一次写入总是成功。
为什么 BufferedWriter 不能在第一次写入时抛出异常?毕竟套接字在很长一段时间之前都是正常关闭的。该代码还在第一次写入之前对套接字进行读取,返回 -1 以表明输入端已经检测到套接字关闭。为什么输出端也不能知道这个?
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9000);
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine());
s.close();
System.out.println("Socket closed");
}
}
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = new Socket("localhost", 9000);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
out.write("Hello, World!\n"); out.flush();
Thread.sleep(10000);
System.out.println("Read from socket returns: " + s.getInputStream().read());
out.write("First write\n"); out.flush();
System.out.println("First write succeeded without detecting socket closed");
out.write("Second write\n"); out.flush();
System.out.println("Second write succeeded without detecting socket closed");
}
}