package cn.bunny.file_dir;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

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

        // 创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        SelectionKey selectionKey = serverSocketChannel.register(selector, 0, null);

        // 只关注channel
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);
        System.out.println(STR."注册时的key：\{selectionKey}");

        // 模拟监听端口
        serverSocketChannel.bind(new InetSocketAddress(8080));

        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 需要移出key，在事件集合中需要移出
                iterator.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel cancel = (ServerSocketChannel) key.channel();
                    SocketChannel accept = cancel.accept();
                    accept.configureBlocking(false);
                    SelectionKey scKey = accept.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);
                    System.out.println(STR."accept的key\{accept}");
                    System.out.println(STR."scKey\{scKey}");
                } else if (key.isReadable()) {
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        // 如果客户端断开，这里会报错
                        channel.read(buffer);
                        buffer.flip();
                    } catch (IOException exception) {
                        exception.printStackTrace();
                        // 断开后会进行删除
                        key.cancel();
                    }

                }
            }
        }
    }
}
