JAVA NIO客户端主动关闭连接,导致服务器空轮询

查看:653
本文介绍了JAVA NIO客户端主动关闭连接,导致服务器空轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

当客户端连接关闭时,服务器select()不会阻塞,然后一直分发读就绪操作,且读到的字节长度都是0,这是什么情况。

服务器代码

public class NIOServerTest {
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverChannel = ServerSocketChannel.open();
            serverChannel.bind(new InetSocketAddress(666));
            serverChannel.configureBlocking(false);
            Selector selector = Selector.open();
            serverChannel.register(selector,SelectionKey.OP_ACCEPT);
            while(true){
                int count = selector.select(); //阻塞
                if(count>0){
                    Set<SelectionKey> keys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = keys.iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isAcceptable()){
                            System.out.println("client connect");
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            SocketChannel sc = serverSocketChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                        }
                        if(key.isReadable()){
                            SocketChannel socketChannel = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(512);
                            socketChannel.read(buffer);
                            buffer.flip();
                            System.out.println("on read size:"+buffer.remaining());
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端代码

public class NIOClientTest{
    public static void main(String[] args) throws UnknownHostException, IOException{
        try {
            Socket socket = new Socket("127.0.0.1",666);
            try(OutputStreamWriter output = new OutputStreamWriter(socket.getOutputStream());){
                output.write(1);
                output.flush();
            }catch (Exception e) {
                e.printStackTrace();
            }
            socket.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
    }
}

解决方案

当客户端主动切断连接的时候,服务端 Socket 的读事件(FD_READ)仍然起作用,也就是说,服务端 Socket 的状态仍然是有东西可读,当然此时读出来的字节肯定是 0。

socketChannel.read(buffer) 是有返回值的,这种情况下返回值是 -1,所以如果 read 方法返回的是 -1,就可以关闭和这个客户端的连接了。

这种情况也有可能会抛出 IOException,需要捕获异常并判断。

这篇关于JAVA NIO客户端主动关闭连接,导致服务器空轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆