ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

NIO详解及应用(一)

2022-03-01 20:02:01  阅读:160  来源: 互联网

标签:NIO System println 详解 应用 inChannel 缓冲区 buf out


一、基础详解

1、传统IO(BIO)

传统IO是面向流的,是同步阻塞式IO。每次socket请求都需要对应一个线程去处理,如果没有足够的线程处理,要么请求就是在等待,要么被拒绝。也就是每一个连接,都要求服务对应一个线程去处理。这也就是传统IO效率低下的原因。

2、NIO(NIO 1.0或New IO或 Non Blocking IO)

因为传统IO效率低下,因此在JDK1.4及以后版本中提供了一套API来专门操作非阻塞I/O,它可以替代标准的Java IO API。

注:传统的的I/O包已经使用NIO重新实现过,即使我们使用传统的IO,也是会比原来的效率高。

NIO运用了事件驱动思想,基于Reactor(本文会讲解),当socket有流可读或可写入socket时,操作系统会相应的通知引用程序进行处理,应用再将流读取到缓冲区或写入操作系统。(不在是每个请求对应一个线程处理,而是一个线程不断的轮询每个IO操作的状态)。

NIO支持面向缓冲区的、基于通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。由三个主要的部分组成:缓冲区(Buffers)、通道(Channels)和选择器(Selector)。 后续我们一个一个讲解。
重要的一句话:NIO和传统IO之间第一个最大的区别是,IO是面向流的,NIO是面向缓冲区的。

3、AIO(NIO 2.0)

异步非阻塞的IO,也就是无需像NIO似的一个线程去轮询所有IO操作的状态改变,在相应的状态改变后,系统会通知对应的线程来处理。
在JDK1.7中,java.nio.channels包下增加了四个异步通道:

  1. AsynchronousSocketChannel
  2. AsynchronousServerSocketChannel
  3. AsynchronousFileChannel
  4. AsynchronousDatagramChannel

其中的read/write方法,会返回一个带回调函数的对象,当执行完读取/写入操作后,直接调用回调函数。

AIO不是本文研究的重点,仅做简要介绍。

二、NIO三大组成部分详解

1、缓冲区(Buffer )

缓冲区(Buffer) :一个用于特定基本数据类型的容器。由 java.nio 包定义的,所有缓冲区(ByteBuffe、CharBuffer、 ShortBuffer、IntBuffer、LongBuffer、FloatBuffer、DoubleBuffer)都是 Buffer 抽象类的子类。

在NIO库中,所有数据都是用缓冲区处理的。在读取数据时,它是直接读到缓冲区中的;在写入数据时,也是写入到缓冲区中。任何时候访问NIO中的数据,都是通过缓冲区进行操作。

缓冲区中的四个核心属性:

  • capacity:容量,表示缓冲区中最大存储数据的容量。一旦声明不能改变。
  • limit:界限,表示缓冲区中可以操作数据的大小。(limit后数据不能进行读写)
  • position:位置,表示缓冲区中正在操作数据的位置。
  • mark:标记,表示记录当前position位置。可以通过reset()恢复到mark的位置。
    注意:0 <= mark <= position <= limit <= capacity

缓冲区实际上是一个数组,并提供了对数据结构化访问以及维护读写位置等信息,请参照四个核心属性看下图。
在这里插入图片描述
缓冲区存取数据的两个核心方法:

  • put():存入数据到缓冲区中
    put(byte b):将给定单个字节写入缓冲区的当前位置
    put(byte[] src):将 src 中的字节写入缓冲区的当前位置
    put(int index, byte b):将指定字节写入缓冲区的索引位置(不会移动 position)
  • get():获取缓存区中的数据
    get():读取单个字节
    get(byte[] dst):批量读取多个字节到 dst 中
    get(int index):读取指定索引位置的字节(不会移动 position)

常用方法大概知道一下就行:
在这里插入图片描述
操作缓冲区的代码如下,可以简单看看,便于理解,后续我们使用NIO时不会亲自操作这些代码。

@Test
public void test1(){
	String str = "abcd";
	
	//1. 分配一个指定大小的缓冲区
	ByteBuffer buf = ByteBuffer.allocate(1024);
	
	System.out.println("-----------------allocate() 创建----------------");
	System.out.println("position = "+buf.position());
	System.out.println("limit= "+buf.limit());
	System.out.println("capacity = "+buf.capacity());
	
	//2. 利用 put() 存入数据到缓冲区中
	buf.put(str.getBytes());
	
	System.out.println("-----------------put() 存储----------------");
	System.out.println("position = "+buf.position());
	System.out.println("limit = "+buf.limit());
	System.out.println("capacity = "+buf.capacity());
	
	//3. 切换读取数据模式
	buf.flip();
	
	System.out.println("-----------------flip()----------------");
	System.out.println("position = "+buf.position());
	System.out.println("limit = "+buf.limit());
	System.out.println("capacity = "+buf.capacity());
	
	//4. 利用 get() 读取缓冲区中的数据
	byte[] dst = new byte[buf.limit()];
	buf.get(dst);
	System.out.println(new String(dst, 0, dst.length));
	
	System.out.println("-----------------get() 读取----------------");
	System.out.println("position = "+buf.position());
	System.out.println("limit = "+buf.limit());
	System.out.println("capacity = "+buf.capacity());
	
	//5. rewind() : 可重复读
	buf.rewind();
	
	System.out.println("-----------------rewind() 可重复读----------------");
	System.out.println("position = "+buf.position());
	System.out.println("limit = "+buf.limit());
	System.out.println("capacity = "+buf.capacity());
	
	//6. clear() : 清空缓冲区. 但是缓冲区中的数据依然存在,但是处于“被遗忘”状态
	buf.clear();
	
	System.out.println("-----------------clear()----------------");
	System.out.println("position = "+buf.position());
	System.out.println("limit = "+buf.limit());
	System.out.println("capacity = "+buf.capacity());
	
	System.out.println((char)buf.get());	
}

运行结果如下:

-----------------allocate() 创建----------------
position = 0
limit= 1024
capacity = 1024
-----------------put() 存储----------------
position = 4
limit = 1024
capacity = 1024
-----------------flip()----------------
position = 0
limit = 4
capacity = 1024
abcd
-----------------get() 读取----------------
position = 4
limit = 4
capacity = 1024
-----------------rewind() 可重复读----------------
position = 0
limit = 4
capacity = 1024
-----------------clear()----------------
position = 0
limit = 1024
capacity = 1024
a

mark() : 标记 ,表示记录当前 position 的位置。
reset() : 恢复到 mark 的位置。
关于mark()、reset() 的使用,可以根据下方代码理解。

@Test
public void test2(){
	String str = "abcde";
	
	ByteBuffer buf = ByteBuffer.allocate(1024);
	
	buf.put(str.getBytes());
	
	buf.flip();
	
	byte[] dst = new byte[buf.limit()];
	buf.get(dst, 0, 2);
	System.out.println(new String(dst, 0, 2));
	System.out.println("position1 = "+buf.position());
	
	//mark() : 标记 position=2
	buf.mark();
	
	buf.get(dst, 2, 2);
	System.out.println(new String(dst, 2, 2));
	System.out.println("position2 = "+buf.position());
	
	//reset() : 恢复到 mark 的位置
	buf.reset();
	System.out.println("position3 = "+buf.position());
	
	//判断缓冲区中是否还有剩余数据
	if(buf.hasRemaining()){
		
		//获取缓冲区中可以操作的数量
		System.out.println(buf.remaining());
	}
}

上方代码只是便于理解,如果理解了,可以不用看代码实现,真正操作时不会去手动写这些原理级代码的。

NIO的缓冲区分为非直接缓冲区和非直接缓冲区。

1.1非直接缓冲区:
在这里插入图片描述
使用非直接缓冲区时,也就是通过allocate()方法分配缓冲区,将缓冲区建立在JVM的内存中,当我们的程序想要从硬盘中读取数据,需要如下三步:

1.先从物理硬盘把数据读取到物理内存中

2再将内容复制到JVM的内存中

3然后读取应用程序才可以读取到内容

读写都是这样需要复制这一个动作,缺点是速度慢,优点是安全

代码如下:

/**
	 * 非直接缓冲区 读写操作
	 * @throws IOException
	 */
	@Test
	public void test001() throws IOException {
		long statTime=System.currentTimeMillis();
		// 读入流
		FileInputStream fst = new FileInputStream("f://1.mp4");
		// 写入流
		FileOutputStream fos = new FileOutputStream("f://2.mp4");
		// 创建通道
		FileChannel inChannel = fst.getChannel();
		FileChannel outChannel = fos.getChannel();
		// 分配指定大小缓冲区
		ByteBuffer buf = ByteBuffer.allocate(1024);
		while (inChannel.read(buf) != -1) {
			// 开启读取模式
			buf.flip();
			// 将数据写入到通道中
			outChannel.write(buf);
			buf.clear();
		}
		// 关闭通道 、关闭连接
		inChannel.close();
		outChannel.close();
		fos.close();
		fst.close();
		long endTime=System.currentTimeMillis();
		System.out.println("操作非直接缓冲区耗时时间:"+(endTime-statTime));
	}

1.2直接缓冲区:
在这里插入图片描述
使用直接缓冲区,是在应用程序和物理磁盘中直接在内存中建立一个缓冲区在物理内存中,这样省略了复制的步骤。(通过allocateDirect()方法分配直接缓冲区,将缓冲区建立在物理内存中)

/**
	 * 直接缓冲区
	 * @throws IOException
	 */
	@Test
	public void test002() throws IOException {
		long statTime=System.currentTimeMillis();
		//创建管道
		FileChannel  inChannel=	FileChannel.open(Paths.get("f://1.mp4"), StandardOpenOption.READ);
		FileChannel  outChannel=FileChannel.open(Paths.get("f://2.mp4"), StandardOpenOption.READ,StandardOpenOption.WRITE, StandardOpenOption.CREATE);
	    //定义映射文件
		MappedByteBuffer inMappedByte = inChannel.map(MapMode.READ_ONLY,0, inChannel.size());
		MappedByteBuffer outMappedByte = outChannel.map(MapMode.READ_WRITE,0, inChannel.size());
		//直接对缓冲区操作
		byte[] dsf=new byte[inMappedByte.limit()];
		inMappedByte.get(dsf);
		outMappedByte.put(dsf);
		inChannel.close();
		outChannel.close();
		long endTime=System.currentTimeMillis();
		System.out.println("操作直接缓冲区耗时时间:"+(endTime-statTime));
	}

2、通道(Channel)

Channel表示内存到IO设备(如:文件、套接字)的连接,即用于源节点与目标节点的连接。在java NIO中Channel本身不负责存储和访问数据数据,主要是配合缓冲区(buffer),负责数据的传输。

举一个生动明显的例子来说明操作系统中通道的必要性,首先看一下这个图:
在这里插入图片描述
如果我们使用传统io,也就是不利用通道去进行数据传输,那么我们cpu会负责去直接调用io接口,然后进行直接缓冲区/非直接缓冲区的交互。

如果我们使用了通道,在需要进行I/O操作时,cpu只需启动通道,然后cpu自己可以继续执行自身程序,通道则执行通道程序,也就是说通道使主机(CPU和内存)与I/O操作之间达到更高的并行程度

通道内部运行图如下:
在这里插入图片描述
通道的相关方法和代码如下(还是那句话,了解即可,应用时候这些都是内部实现了):

/*
 * 一、通道(Channel):用于源节点与目标节点的连接。在java NIO中负责缓冲区中数据的传输。Channel本身不存储数据,需要配合缓冲区进行传输。
 * 
 * 二、通道的主要实现类
 *    java.nio.channels.Channel 接口:
 *        |--FileChannel:用于读取、写入、映射和操作文件的通道。
 *        |--SocketChannel:通过 TCP 读写网络中的数据。
 *        |--ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。
 *        |--DatagramChannel:通过 UDP 读写网络中的数据通道。
 *        
 * 三、获取通道
 * 1.java针对支持通道的类提供了getChannel()方法
 *      本地IO:
 *      FileInputStream/FileOutputStream
 *      RandomAccessFile
 *      
 *      网络IO:
 *      Socket
 *      ServerSocket
 *      DatagramSocket
 *      
 * 2.在JDK 1.7 中的NIO.2 针对各个通道提供了静态方法 open()
 * 3.在JDK 1.7 中的NIO.2 的Files工具类的newByteChannel()
 * 
 * 四、通道之间的数据传输
 * transferFrom()
 * transferTo()
 * 
 * 五、分散(Scatter)与聚集(Gather)
 * 分散读取(Scattering Reads):将通道中的数据分散到多个缓冲区中
 * 聚集写入(Gathering Writes):将多个缓冲区中的数据聚集到通道中
 * 
 * 六、字符集:Charset
 * 编码:字符串-》字符数组
 * 解码:字符数组-》字符串
 */
public class TestChannel {

    //利用通道完成文件的复制(非直接缓冲区)
    @Test
    public void test1(){
        long start=System.currentTimeMillis();

        FileInputStream fis=null;
        FileOutputStream fos=null;

        FileChannel inChannel=null;
        FileChannel outChannel=null;
        try{
            fis=new FileInputStream("d:/1.avi");
            fos=new FileOutputStream("d:/2.avi");

            //1.获取通道
            inChannel=fis.getChannel();
            outChannel=fos.getChannel();

            //2.分配指定大小的缓冲区
            ByteBuffer buf=ByteBuffer.allocate(1024);

            //3.将通道中的数据存入缓冲区中
            while(inChannel.read(buf)!=-1){
                buf.flip();//切换读取数据的模式
                //4.将缓冲区中的数据写入通道中
                outChannel.write(buf);
                buf.clear();//清空缓冲区
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(outChannel!=null){
                try {
                    outChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inChannel!=null){
                try {
                    inChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long end=System.currentTimeMillis();
        System.out.println("耗费时间:"+(end-start));//耗费时间:1094
    }

    //使用直接缓冲区完成文件的复制(内存映射文件)
    @Test
    public void test2() {
        long start=System.currentTimeMillis();

        FileChannel inChannel=null;
        FileChannel outChannel=null;
        try {
            inChannel = FileChannel.open(Paths.get("d:/1.avi"), StandardOpenOption.READ);
            outChannel=FileChannel.open(Paths.get("d:/2.avi"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);

            //内存映射文件
            MappedByteBuffer inMappedBuf=inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
            MappedByteBuffer outMappedBuf=outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
            //直接对缓冲区进行数据的读写操作
            byte[] dst=new byte[inMappedBuf.limit()];
            inMappedBuf.get(dst);
            outMappedBuf.put(dst);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(outChannel!=null){
                try {
                    outChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inChannel!=null){
                try {
                    inChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        long end=System.currentTimeMillis();
        System.out.println("耗费的时间为:"+(end-start));//耗费的时间为:200
    }

    //通道之间的数据传输(直接缓冲区)
    @Test
    public void test3(){
        long start=System.currentTimeMillis();

        FileChannel inChannel=null;
        FileChannel outChannel=null;
        try {
            inChannel = FileChannel.open(Paths.get("d:/1.avi"), StandardOpenOption.READ);
            outChannel=FileChannel.open(Paths.get("d:/2.avi"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);

            inChannel.transferTo(0, inChannel.size(), outChannel);
            outChannel.transferFrom(inChannel, 0, inChannel.size());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(outChannel!=null){
                try {
                    outChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inChannel!=null){
                try {
                    inChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long end=System.currentTimeMillis();
        System.out.println("耗费的时间为:"+(end-start));//耗费的时间为:147
    }

    //分散和聚集
    @Test
    public void test4(){
        RandomAccessFile raf1=null;
        FileChannel channel1=null;
        RandomAccessFile raf2=null;
        FileChannel channel2=null;
        try {
            raf1=new RandomAccessFile("1.txt","rw");

            //1.获取通道
            channel1=raf1.getChannel();

            //2.分配指定大小的缓冲区
            ByteBuffer buf1=ByteBuffer.allocate(100);
            ByteBuffer buf2=ByteBuffer.allocate(1024);

            //3.分散读取
            ByteBuffer[] bufs={buf1,buf2};
            channel1.read(bufs);

            for(ByteBuffer byteBuffer : bufs){
                byteBuffer.flip();
            }
            System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
            System.out.println("--------------------");
            System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));

            //4.聚集写入
            raf2=new RandomAccessFile("2.txt", "rw");
            channel2=raf2.getChannel();

            channel2.write(bufs);

        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(channel2!=null){
                try {
                    channel2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(channel1!=null){
                try {
                    channel1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf2!=null){
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf1!=null){
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //输出支持的字符集
    @Test
    public void test5(){
        Map<String,Charset> map=Charset.availableCharsets();
        Set<Entry<String,Charset>> set=map.entrySet();

        for(Entry<String,Charset> entry:set){
            System.out.println(entry.getKey()+"="+entry.getValue());
        }
    }

    //字符集
    @Test
    public void test6(){
        Charset cs1=Charset.forName("GBK");

        //获取编码器
        CharsetEncoder ce=cs1.newEncoder();

        //获取解码器
        CharsetDecoder cd=cs1.newDecoder();

        CharBuffer cBuf=CharBuffer.allocate(1024);
        cBuf.put("啦啦哈哈吧吧");
        cBuf.flip();

        //编码
        ByteBuffer bBuf=null;
        try {
            bBuf = ce.encode(cBuf);
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }

        for(int i=0;i<12;i++){
            System.out.println(bBuf.get());//-64-78-64-78-71-2-7-2-80-55-80-55
        }

        //解码
        bBuf.flip();
        CharBuffer cBuf2=null;
        try {
            cBuf2 = cd.decode(bBuf);
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }
        System.out.println(cBuf2.toString());
    }
}

3、选择器(Selector)

Selector负责监控通道的IO状况,也可以叫多路复用器 。它是Java NIO核心组件中的一个,用于检查一个或多个NIO Channel(通道)的状态是否处于可读、可写。如此可以实现单线程管理多个channels,也就是可以管理多个网络链接。

样例代码(了解即可,都封装好了,也是不需要自己写的):

/*
 * 一、使用NIO 完成网络通信的三个核心:
 * 
 * 1、通道(Channel):负责连接
 *      java.nio.channels.Channel 接口:
 *           |--SelectableChannel
 *               |--SocketChannel
 *               |--ServerSocketChannel
 *               |--DatagramChannel
 *               
 *               |--Pipe.SinkChannel
 *               |--Pipe.SourceChannel
 *               
 * 2.缓冲区(Buffer):负责数据的存取
 * 
 * 3.选择器(Selector):是 SelectableChannel 的多路复用器。用于监控SelectableChannel的IO状况
 */
public class TestBlockingNIO {//没用Selector,阻塞型的

    //客户端
    @Test
    public void client() throws IOException{
        SocketChannel sChannel=SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
        FileChannel inChannel=FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
        ByteBuffer buf=ByteBuffer.allocate(1024);
        while(inChannel.read(buf)!=-1){
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }
        sChannel.shutdownOutput();//关闭发送通道,表明发送完毕

        //接收服务端的反馈
        int len=0;
        while((len=sChannel.read(buf))!=-1){
            buf.flip();
            System.out.println(new String(buf.array(),0,len));
            buf.clear();
        }
        inChannel.close();
        sChannel.close();
    }

    //服务端
    @Test
    public void server() throws IOException{
        ServerSocketChannel ssChannel=ServerSocketChannel.open();
        FileChannel outChannel=FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
        ssChannel.bind(new InetSocketAddress(9898));
        SocketChannel sChannel=ssChannel.accept();
        ByteBuffer buf=ByteBuffer.allocate(1024);
        while(sChannel.read(buf)!=-1){
            buf.flip();
            outChannel.write(buf);
            buf.clear();
        }

        //发送反馈给客户端
        buf.put("服务端接收数据成功".getBytes());
        buf.flip();//给为读模式
        sChannel.write(buf);

        sChannel.close();
        outChannel.close();
        ssChannel.close();
    }
}

SelectionKey

SelectionKey:表示通道和选择器之间的注册关系。每次向选择器注册通道时就会选择一个事件(选择键)。选择键包含两个表示为整数值的操作集。操作集的每一位都表示该键的通道所支持的一类可选择操作。

例如:调用 register(Selector sel, int ops) 将通道注册到选择器时,选择器对通道的监听事件,需要通过第二个参数 ops 指定。
ops代表可以监听的事件类型(用 SelectionKey 的四个常量表示):

读 : SelectionKey.OP_READ (1)
写 : SelectionKey.OP_WRITE (4)
连接 : SelectionKey.OP_CONNECT (8)
接收 : SelectionKey.OP_ACCEPT (16)

若注册时不止监听一个事件,则可以使用“位或”操作符连接。

样例代码(了解即可):

public class TestNonBlockingNIO {
    //客户端
    @Test
    public void client()throws IOException{
        //1.获取通道
        SocketChannel sChannel=SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        //2.切换非阻塞模式
        sChannel.configureBlocking(false);
        //3.分配指定大小的缓冲区
        ByteBuffer buf=ByteBuffer.allocate(1024);
        //4.发送数据给服务端
        Scanner scan=new Scanner(System.in);
        while(scan.hasNext()){
            String str=scan.next();
            buf.put((new Date().toString()+"\n"+str).getBytes());
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }
        //5.关闭通道
        sChannel.close();
    }

    //服务端
    @Test
    public void server() throws IOException{
        //1.获取通道
        ServerSocketChannel ssChannel=ServerSocketChannel.open();

        //2.切换非阻塞式模式
        ssChannel.configureBlocking(false);

        //3.绑定连接
        ssChannel.bind(new InetSocketAddress(9898));

        //4.获取选择器
        Selector selector=Selector.open();

        //5.将通道注册到选择器上,并且指定“监听接收事件”
        ssChannel.register(selector,SelectionKey.OP_ACCEPT);

        //6.轮询式的获取选择器上已经“准备就绪”的事件
        while(selector.select()>0){

            //7.获取当前选择器中所有注册的“选择键(已就绪的监听事件)”
            Iterator<SelectionKey> it=selector.selectedKeys().iterator();

            while(it.hasNext()){
                //8.获取准备“就绪”的事件
                SelectionKey sk=it.next();

                //9.判断具体是什么时间准备就绪
                if(sk.isAcceptable()){
                    //10.若“接收就绪”,获取客户端连接
                    SocketChannel sChannel=ssChannel.accept();

                    //11.切换非阻塞模式
                    sChannel.configureBlocking(false);

                    //12.将该通道注册到选择器上
                    sChannel.register(selector, SelectionKey.OP_READ);
                }else if(sk.isReadable()){
                    //13.获取当前选择器上“读就绪”状态的通道
                    SocketChannel sChannel=(SocketChannel)sk.channel();
                    //14.读取数据
                    ByteBuffer buf=ByteBuffer.allocate(1024);
                    int len=0;
                    while((len=sChannel.read(buf))>0){
                        buf.flip();
                        System.out.println(new String(buf.array(),0,len));
                        buf.clear();
                    }
                }
                //15.取消选择键SelectionKey
                it.remove();
            }
        }
    }
}

标签:NIO,System,println,详解,应用,inChannel,缓冲区,buf,out
来源: https://blog.csdn.net/qq_42969135/article/details/122090320

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有