我在任何地方都找不到这个问题的满意答案。了解内部结构的人可以解释一下吗?
我写了一个简单的客户端/服务器来演示这个问题。 服务器读取一行文本然后关闭套接字。客户端写入一行文本,等待 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");
}
}
最佳答案
远程关闭与远程关闭输出没有区别。在这两种情况下,这一端都会收到 FIN,这意味着对等端已停止发送。没有迹象表明他已停止接收,即使事实上他已关闭输入。因此,发送方可以检测到的唯一方法是在发送时获取 RST,根据定义,这不会发生在第一次发送时,除非发送的数据可能大于套接字发送缓冲区。
关于java - 首先写入远程关闭的套接字不会触发异常,可以吗? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15275750/