+
 新版

nio selector问题

osc_47904062 发布于 2022/09/27 09:23
阅读 258
收藏 0

 

 

这个代码里已经ServerSocketChannel ssc = ServerSocketChannel.open();为什么下面迭代的时候还ServerSocketChannel channel = (ServerSocketChannel) key.channel(); 

serversocket不是等待客户端链接的吗。有点不太明白。希望大神解答一下。

 

public class Server {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);

        SelectionKey ssckey = ssc.register(selector, 0, null);
        ssckey.interestOps(SelectionKey.OP_ACCEPT);

        System.out.println(ssckey);

        while (true){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                System.out.println(key);

                ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                channel.accept();
                
            }
        }
    }
}
加载中
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部