【NIO服务器代码-可测试】

蹲街弑〆低调 提交于 2020-03-14 18:14:27

1、目的:了解NIO服务的工作原理

2、代码:

/**
 * @Author: Liu
 * @Descripition:NIO测试
 * @Date; Create in 2020/3/14 16:10
 **/
public class NIOServerDemo {

    private int port = 8080;

    private Selector selector;

    private ByteBuffer buffer = ByteBuffer.allocate(1024);

    //初始化完毕
    public NIOServerDemo(int port) {

        this.port = port;
        try {
            ServerSocketChannel server = ServerSocketChannel.open();
            server.bind(new InetSocketAddress(this.port));
            //设置非阻塞
            server.configureBlocking(false);

            selector = Selector.open();
            server.register(selector, SelectionKey.OP_ACCEPT);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        System.out.println("listen on " + this.port + ".");

        try {
            while (true) {
                selector.select();

                Set<SelectionKey> selectionKeys = selector.selectedKeys();

                Iterator<SelectionKey> iterator = selectionKeys.iterator();

                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();

                    iterator.remove();
                    //数据就绪,数据可读,可写等 看key的方法
                    process(key);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //具体办理业务的方法,处理业务逻辑
    //每次轮询调用一次,同步
    private void process(SelectionKey key) throws IOException {
        //针对每一种状态有一个反应
        if (key.isAcceptable()) {
            ServerSocketChannel channel = (ServerSocketChannel) key.channel();
            //体现非阻塞,返回一个状态和反馈
            SocketChannel accept = channel.accept();
            channel.configureBlocking(false);
            key = channel.register(selector, SelectionKey.OP_READ);

        } else if (key.isReadable()) {
            SocketChannel channel = (SocketChannel) key.channel();
            int read = channel.read(buffer);
            if (read > 0) {
                buffer.flip();

                String content = new String(buffer.array(), 0, read);
                SelectionKey register = channel.register(selector, SelectionKey.OP_READ);
                register.attach(content);
                System.out.println("读取内容:" + content);

            }
        } else if (key.isWritable()) {
            SocketChannel channel = (SocketChannel) key.channel();
            String content = (String) key.attachment();
            channel.write(ByteBuffer.wrap(("输出:" + content).getBytes()));
            channel.close();
        }

    }

    public static void main(String[] args) {
        new NIOServerDemo(8080).listen();
    }
}

每天提高一点点

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!