Java系列6 NIO

2019-02-11  本文已影响0人  莫小归

参考:
https://www.jianshu.com/p/362b365e1bcc
https://www.jianshu.com/p/5d2c68b89f1d
https://www.jianshu.com/p/389e4571cd2c

一.NIO产生背景

二.NIO核心实现

NIO核心API Channel,Buffer,Selector。数据总是从Chanel读取到Buffer,或从Buffer写入Channel

1.通道Channel
2.缓冲区Buffer

3.Selector

三.NIO常用方法

1.Buffer类的flip、clear、compact方法

本质是设置控制Buffer状态的position、limit、capacity三个变量

public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
 }
flip方法变读状态为写状态
public final Buffer clear() {
    position = 0;
    limit = capacity;
    mark = -1;
    return this;
}
clear方法将缓冲区position清零

2.Channel类

channel.configureBlocking(false);  //设置channel为非阻塞
SelectionKey key =channel.register(selector,SelectionKey.OP_READ);  //注册channel

3.Selector类

Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) { 
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
    // a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
    // a connection was established with a remote server.
} else if (key.isReadable()) {
    // a channel is ready for reading
} else if (key.isWritable()) {
    // a channel is ready for writing
}
keyIterator.remove();
}

四.NIO实践

1.从文件读取数据

FileInputStream fin = new FileInputStream("ReadTest.txt");
FileChanel fc = fim.getChannel();  //获取通道
ByteBuffer buffer = ByteBuffer.allocate(1024);  //创建缓冲区
fc.read(buffer);  //从通道读入数据到缓冲区
FileOutputStream fout = new FileOutputStream("WriteTest.txt");
FileChannel fc = fout.getChannel;  //获取通道
ByteBuffer buffer = ByteBuffer.allocate(1024);  //创建缓冲区
for(int i = 0 ; i < message.length ; i++) {
  buffer.put( message[i] );
}    //将数据放入缓冲区
buffer.flip();  //切换缓冲区为写模式
fc.write(buffer);  //将缓冲区内容写入通道
/**
 * 用java NIO api拷贝文件
 * @param src
 * @param dst
 * @throws IOException
 */
public static void copyFileUseNIO(String src,String dst) throws IOException{
    //声明源文件和目标文件
            FileInputStream fi=new FileInputStream(new File(src));
            FileOutputStream fo=new FileOutputStream(new File(dst));
            //获得传输通道channel
            FileChannel inChannel=fi.getChannel();
            FileChannel outChannel=fo.getChannel();
            //获得容器buffer
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            while(true){
                //判断是否读完文件
                int eof =inChannel.read(buffer);
                if(eof==-1){
                    break;  
                }
                //重设一下buffer的position=0,limit=position
                buffer.flip();
                //开始写
                outChannel.write(buffer);
                //写完要重置buffer,重设position=0,limit=capacity
                buffer.clear();
            }
            inChannel.close();
            outChannel.close();
            fi.close();
            fo.close();
}     

2.网络Socket使用NIO

  public void client() throws Exception{
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 3000));
        socketChannel.configureBlocking(false);
        
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            String str = scanner.next();
            buffer.put(str.getBytes());
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
public void server() throws Exception {
        // 获取通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        // 设置为非阻塞
        serverChannel.configureBlocking(false);
        // 绑定端口
        serverChannel.bind(new InetSocketAddress(3000));

        // 创建连接器
        Selector selector = Selector.open();
        // 将连接器注册到channel,并设置监听事件(接受事件)
        // SelectionKey.OP_CONNECT:链接状态
        // SelectionKey.OP_READ:读状态
        // SelectionKey.OP_WRITE:写状态
        // SelectionKey.OP_ACCEPT:接受状态,当接受准备就绪,开始进行下一步操作
        // 通过 | 进行链接可以监听多个状态
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 轮寻获取选择器上已经准备就绪的状态
        while (selector.select() > 0) {
            // 获取所有的监听Key
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    // 若获取状态就绪,就获取客户端的链接
                    SocketChannel clientChannel = serverChannel.accept();
                    // 将客户端的链接设置为非阻塞状态
                    clientChannel.configureBlocking(false);
                    // 给该通道注册到选择器上,并设置状态为读就绪
                    clientChannel.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = channel.read(buffer)) > 0) {
                        buffer.flip();
                        System.out.println(new String(buffer.array(), 0, len));
                        buffer.clear();
                    }
                }
                // 取消处理完了的选择建
                iterator.remove();
            }
        }
    }

愿将腰下剑,直为斩楼兰

上一篇 下一篇

猜你喜欢

热点阅读