关闭socket时不会抛出异常

Alf*_*rio 2 java sockets

当服务器套接字关闭时,即使在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();
    }

}
Run Code Online (Sandbox Code Playgroud)

公共类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.");       
    }

}
Run Code Online (Sandbox Code Playgroud)

我所做的是启动 ModemServerSocket 应用程序,然后启动 ModemClientSocket 应用程序。

ModemServerSocket 输出

hello 
q
Run Code Online (Sandbox Code Playgroud)

ModemClientSocket 输出

Whoop. No exception. The client didn't notice.
Run Code Online (Sandbox Code Playgroud)

这是预期的行为吗?为什么会出现这样的情况呢?

然而,我做了另一个测试,我关闭了 ModemClientSocket ,而 ModemServerSocket 尝试从 InputStream 中读取,在这种情况下,我得到了一个java.net.SocketException,这正是我所期望的。奇怪的是PrintWriter (OutputStream)没有发生这种情况,也没有抛出异常。

我使用Java 1.6.0 Update 26进行测试。