使用Nio的时候 发现在客户端强行关闭后 服务端的channel还能read channel的状态还是为connected?

新手上路,请多包涵

问题描述

使用Nio的时候 发现在客户端强行关闭后 服务端的channel还能read

相关代码

服务端:

public class NBserver {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        SelectionKey sscKey = serverSocketChannel.register(selector, 0, null);
        sscKey.interestOps(SelectionKey.OP_ACCEPT);


        serverSocketChannel.bind(new InetSocketAddress(8080));
        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    System.out.println("new connect: " + sc);
                    sc.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    channel.read(buffer);
                    System.out.println(channel);
                    buffer.flip();
                    ByteBufferUtil.debugRead(buffer);
                }
                iterator.remove();
            }
        }
    }
}

客户端:

public class Bclient {
    public static void main(String[] args) throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("localhost",8080));
        SocketAddress ad = sc.getLocalAddress();
        System.out.println("waiting---");
    }
}

你期待的结果是什么?实际看到的错误信息又是什么?

我认为的结果应该是,客户端强行关闭后,服务端的channel再去read的话应该是报
java.io.IOException: 远程主机强迫关闭了一个现有的连接 这个异常才对,然而实际的结果是一直触发读事件,且channel的状态是connected。一直触发读事件的原因我知道,请帮忙解释一下,为啥此时的channel状态还是connected
image.png

阅读 822
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题