设为首页 加入收藏

TOP

Java I/O(4):AIO和NIO中的Selector(三)
2023-07-25 21:25:59 】 浏览:60
Tags:Java I/O AIO NIO Selector
8080)); } else { throw new RuntimeException("channel not opened!"); } // 处理client连接 channel.accept(null, new AioServerHandler(channel)); System.out.println("server started"); // 阻塞主进程 for(;;) { TimeUnit.SECONDS.sleep(1); } } public static void main(String[] args) throws IOException, InterruptedException { AioServer server = new AioServer(); server.start(); } }

 

/**
 * AIO服务端CompletionHandler
 *
 * @author xiangwang
 */
public class AioServerHandler implements CompletionHandler<AsynchronousSocketChannel, Void> {
    private final AsynchronousServerSocketChannel serverChannel;
    private final CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
    private final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    public AioServerHandler(AsynchronousServerSocketChannel serverChannel) {
        this.serverChannel = serverChannel;
    }
    @Override
    public void failed(Throwable exc, Void attachment) {
        // 处理下一次的client连接
        serverChannel.accept(null, this);
    }
    @Override
    public void completed(AsynchronousSocketChannel result, Void attachment) {
        // 处理下一次的client连接,类似链式调用
        serverChannel.accept(null, this);
        try {
            // 将输入内容写到buffer
            String line = input.readLine();
            result.write(ByteBuffer.wrap(line.getBytes()));
            // 在操作系统中的Java本地方法native已经把数据写到了buffer中
            // 这里只需要一个缓冲区能接收就行了
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (result.read(buffer).get() != -1) {
                buffer.flip();
                System.out.println("from client: " + decoder.decode(buffer).toString());
                if (buffer.hasRemaining()) {
                    buffer.compact();
                } else {
                    buffer.clear();
                }
                // 将输入内容写到buffer
                line = input.readLine();
                result.write(ByteBuffer.wrap(line.getBytes()));
            }
        } catch (InterruptedException | ExecutionException | IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

执行测试后显示,不管是在客户端还是在服务端,读写完全是异步的。

 

 


 

 

感谢您的大驾光临!咨询技术、产品、运营和管理相关问题,请关注后留言。欢迎骚扰,不胜荣幸~

 

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇fastJson如何将json与对象、集合.. 下一篇为了讲明白继承和super、this关键..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目