NIO 使用的简单例子

1.FileChannel
fileChannel 是阻塞的,不可以运行在非阻塞模式,因此不能被注册到 Selector 上
简单例子如下:

File f = new File("abcd");
        File f2 = new File("abcd2");
        try (RandomAccessFile accessFile = new RandomAccessFile(f, "r");
            RandomAccessFile accessFile2 = new RandomAccessFile(f2, "rw");
            FileChannel fileChannel = accessFile.getChannel();
            FileChannel fileChannel2 = accessFile2.getChannel();)
        {
            fileChannel2.position(fileChannel2.size());
            ByteBuffer buffer = ByteBuffer.allocate(128);
            while (fileChannel.read(buffer) > 0)
            {
                buffer.flip();
                while (buffer.hasRemaining())
                {
                    fileChannel2.write(buffer);
                }
                buffer.clear();
                System.out.println("------");
            }
        }

RandomAccessFile中获取FileChannel,通过ByteBuffer可以从FileChannel中读取数据也可以向FileChannel写入数据,注意写数据时需要使用 while 循环,因为不能保证 ByteBuffer 一次性将数据全部写入.fileChannel.force(true)方法强制将内存数据同步到磁盘(boolean 参数表示是否将文件元数据写入(权限信息等)).注意ByteBuffer读写之间需要调用方法flip,切换读写模式

2.使用 Selector
只有非阻塞的 channel 才能注册到 selector 上,因此必须使用非阻塞 channel,此处使用 socketChannel 与 socketServerChannel 来做示范,示例代码如下:

客户端代码:

public class SocketNio
{

    private static Charset charset = Charset.forName("UTF-8");

    private static int IO_LENGTH = 20;

    private static int BUFFER_SIZE = 128;

    private static int PORT = 8090;

    public static void main(String[] args)
        throws IOException
    {
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress(PORT));
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        while (true)
        {
            String s = input.nextLine();
            buffer.clear();
            for (int i = 0; i < Math.ceil(s.length() / (double)IO_LENGTH); i++)
            {
                buffer.put(charset.encode(i * IO_LENGTH + IO_LENGTH > s.length() ? s.substring(i * IO_LENGTH)
                    : s.substring(i * IO_LENGTH, i * IO_LENGTH + IO_LENGTH)));
                buffer.flip();
                while (buffer.hasRemaining())
                {
                    channel.write(buffer);
                }
                buffer.clear();
            }
        }
    }
}

客户端仅仅实现了一个发送数据的功能

服务端代码如下:

public class SocketServerNIO
{

    private static Charset charset = Charset.forName("UTF-8");

    private static int PORT = 8090;

    private static int BUFFER_SIZE = 128;

    public static void main(String[] args)
        throws IOException
    {
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.bind(new InetSocketAddress(PORT));
        channel.configureBlocking(false);
        final Selector selector = Selector.open();
        channel.register(selector, SelectionKey.OP_ACCEPT);
        while (selector.select() > 0)
        {
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            while (keyIterator.hasNext())
            {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable())
                {
                    SocketChannel sc = ((ServerSocketChannel)key.channel()).accept();
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                    // 将sk对应的Channel设置成准备接受其他请求
                    key.interestOps(SelectionKey.OP_ACCEPT);
                }
                if (key.isReadable())
                {
                    // 获取该SelectionKey对应的Channel
                    SocketChannel sc = (SocketChannel)key.channel();
                    ByteBuffer buff = ByteBuffer.allocate(BUFFER_SIZE);
                    String content = "";
                    try
                    {
                        while (sc.read(buff) > 0)
                        {
                            buff.flip();
                            content += charset.decode(buff);
                            buff.clear();
                        }
                        System.out.println("读取的数据:" + content);
                        key.interestOps(SelectionKey.OP_READ);
                    }
                    // 如果捕获到带sk对应的Channel出现了异常,即表明该Channel对应的Client出现了问题,
                    // 所以从Selector中取消sk的注册
                    catch (IOException e)
                    {
                        keyIterator.remove();
                        key.cancel();
                        if (key.channel() != null)
                            key.channel().close();
                    }
                }
                keyIterator.remove();
            }
        }
    }
}

服务端将 socketServerChannel 与每一个客户端连接的 socketChannel 均加入到 selector 监听,每当检测到有数据写入时,服务端就将写入数据打印出来,注意每个被注册的 channel 均被设置为非阻塞模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值