ICode9

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

网络IO模型(BIO,NIO,AIO)

2021-08-22 11:03:56  阅读:280  来源: 互联网

标签:BIO java NIO abstract AIO 线程 ByteBuffer import public


网络IO模型

I/O 模型简单的理解:就是用什么样的通道进行数据的发送和接收,很大程度上决定了程序通信的性能.Java共支持3种网络编程模型/IO模式:BIO、NIO、AIO

Java BIO : 同步并阻塞(传统阻塞型),服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销 

Java NIO : 同步非阻塞,服务器实现模式为一个线程处理多个请求(连接),即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有I/O请求就进行处理 

Java AIO(NIO.2) : 异步非阻塞,AIO 引入异步通道的概念,采用了 Proactor 模式,简化了程序编写,有效的请求才启动线程,它的特点是先由操作系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较多且连接时间较长的应用

BIO、NIO、AIO适用场景分析

BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,但程序简单易理解。

NIO方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,弹幕系统,服务器间通讯等。编程比较复杂,JDK1.4开始支持。

AIO方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调用OS参与并发操作,编程比较复杂,JDK7开始支持。 

1. Java的BIO

1. Java BIO 就是传统的 java io 编程,其相关的类和接口在 java.io
2. BIO(blocking I/O) : 同步阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需 要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,可以通过线程池机制改善(实 现多个客户连接服务器)。
3. BIO 方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中, JDK1.4 以前的唯一选择,程序简单易理解

1.1 Java BIO 工作机制

 

 BIO完整流程的梳理

1. 服务器端启动一个 ServerSocket
2. 客户端启动 Socket 对服务器进行通信,默认情况下服务器端需要对每个客户 建立一个线程与之通讯
3. 客户端发出请求后, 先咨询服务器是否有线程响应,如果没有则会等待,或者被拒绝
4. 如果有响应,客户端线程会等待请求结束后,在继续执行

 1.2 代码演示

使用 BIO 模型编写一个服务器端,监听 9000 端口,当有客户端连接时,就启动一个线程与之通讯。

package com.brian.netty.io;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class BlockingService {

    public static void main(String[] args) throws IOException {

        // create a cached thread pool
        ExecutorService executorService = Executors.newCachedThreadPool();
        // create a ServerSockets
        ServerSocket serverSocket = new ServerSocket(9000);
        log.info("===== ServerSocket Start =====");
        while (true) {
            log.info("===== waiting the client connect =====");
            //  listening and wait the client connect
            final Socket accept = serverSocket.accept();
            log.info("===== one client connected thread name is: {} =====", Thread.currentThread().getName());
            executorService.execute(() -> {
                try {
                    handle(accept);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /**
     * communicate with client
     *
     * @param socket
     * @throws IOException
     */
    private static void handle(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        //  get input stream by socket
        try (InputStream inputStream = socket.getInputStream()) {
            // loop read the data from client
            while (true) {
                int read = inputStream.read(bytes);
                if (-1 != read) {
                    String clientMessage = new String(bytes, 0, read);
                    log.info("===== thread <{}> get client message: {}", Thread.currentThread().getName(), clientMessage);
                } else {
                    break;
                }
            }
        }
    }
}

使用telnet,开启两个客户端测试

serverSocket端日志如下,可以看到接受到的每个客户端消息分别对应一个线程

1.3 Java BIO 问题分析

1. 每个请求都需要创建独立的线程,与对应的客户端进行数据Read,业务处理,数据Write
2. 当并发数较大时,需要创建大量线程来处理连接,系统资源占用较大
3. 连接建立后,如果当前线程暂时没有数据可读,则线程就阻塞在Read操作上,造成线程资源浪费

2. Java的NIO

1. JavaNIO全称java non-blocking IO,是指JDK提供的新API。从JDK1.4开始,Java提供了一系列改进的输入/输出的新特性,被统称为NIO(即New IO),是同步非阻塞的
2. NIO相关类都被放在java.nio 包及子包下,并且对原java.io包中的很多类进行改写
3. NIO有三大核心部分:Channel(通道),Buffer(缓冲区),Selector(选择器)
4. NIO是面向缓冲区 ,或者面向块编程的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络
5. JavaNIO的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,
所以直至数据变的可以读取之前,该线程可以继续做其他的事情。 非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情 6. 通俗理解:NIO是可以做到用一个线程来处理多个操作的。假设有10000个请求过来,根据实际情况,可以分配50或者100个线程来处理。不像之前的阻塞IO那样,非得分配10000个 7. HTTP2.0使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求的数量比HTTP1.1大了好几个数量级

2.1 NIO 和 BIO 的比较

1. BIO以流的方式处理数据,而NIO以块的方式处理数据,块I/O的效率比流I/O高很多
2. BIO是阻塞的,NIO则是非阻塞的
3. BIO基于字节流和字符流进行操作,而NIO基于Channel(通道)和Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。Selector(选择器)用于监听多个通道的事件
(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道

 2.2 NIO的三个核心组件 Buffer,Channel, Selector

1. 每个Channel都会对应一个的Buffer
2. Selector对应一个线程, 一个线程对应多个Channel(连接),该图反应了有三个Channel注册到该Selector(程序)
3. 程序切换到哪个Channel是由事件决定的, Event就是一个重要的概念。Selector会根据不同的事件,在各个通道上切换
4. Buffer就是一个内存块,底层是有一个数组。数据的读取写入是通过Buffer,BIO中要么是输入流,或者是输出流不能双向,但是NIO的Buffer是可以读也可以写, 
需要flip()方法切换。Channel是双向的可以返回底层操作系统的情况, 比如Linux底层的操作系统通道就是双向的

2.3 Buffer

缓冲区(Buffer):缓冲区本质上是一个可以读写数据的内存块,可以理解成是一个容器对象(含数组),该对象提供了一组方法可以更轻松地使用内存块,缓冲区对象内置了一些机制,
能够跟踪和记录缓冲区的状态变化情况。Channel提供从文件、网络读取数据的渠道,但是读取或写入的数据都必须经由Buffer

 

2.3.1 Buffer 类及其子类

在 NIO 中,Buffer 是一个顶层父类,它是一个抽象类,底下有六个对应的子类IntBuffer, FloatBuffer, CharBuffer, DoubleBuffer, ShortBuffer, LongBuffer, ByteBuffer.如下图所示,每个子类Buffer都是用数组在缓存数据。

Buffer类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素的信息

 

 Buffer 类及其子类相关方法汇总

public abstract class Buffer {
    //JDK1.4时,引入的api
    public final int capacity()//返回此缓冲区的容量
    public final int position()//返回此缓冲区的位置
    public final Buffer position (int newPositio)//设置此缓冲区的位置
    public final int limit()//返回此缓冲区的限制
    public final Buffer limit (int newLimit)//设置此缓冲区的限制
    public final Buffer mark()//在此缓冲区的位置设置标记
    public final Buffer reset()//将此缓冲区的位置重置为以前标记的位置
    public final Buffer clear()//清除此缓冲区, 即将各个标记恢复到初始状态,但是数据并没有真正擦除, 后面操作会覆盖
    public final Buffer flip()//反转此缓冲区
    public final Buffer rewind()//重绕此缓冲区
    public final int remaining()//返回当前位置与限制之间的元素数
    public final boolean hasRemaining()//告知在当前位置和限制之间是否有元素
    public abstract boolean isReadOnly();//告知此缓冲区是否为只读缓冲区
 
    //JDK1.6时引入的api
    public abstract boolean hasArray();//告知此缓冲区是否具有可访问的底层实现数组
    public abstract Object array();//返回此缓冲区的底层实现数组
    public abstract int arrayOffset();//返回此缓冲区的底层实现数组中第一个缓冲区元素的偏移量
    public abstract boolean isDirect();//告知此缓冲区是否为直接缓冲区
}

Buffer 子类中最常用的是ByteBuffer 类(二进制数据),该类的主要方法如下

public abstract class ByteBuffer {
    //缓冲区创建相关api
    public static ByteBuffer allocateDirect(int capacity)//创建直接缓冲区
    public static ByteBuffer allocate(int capacity)//设置缓冲区的初始容量
    public static ByteBuffer wrap(byte[] array)//把一个数组放到缓冲区中使用
    public static ByteBuffer wrap(byte[] array,int offset, int length)//构造初始化位置offset和上界length的缓冲区

     //缓存区存取相关API
    public abstract byte get( );//从当前位置position上get,get之后,position会自动+1
    public abstract byte get (int index);//从绝对位置get
    public abstract ByteBuffer put (byte b);//从当前位置上添加,put之后,position会自动+1
    public abstract ByteBuffer put (int index, byte b);//从绝对位置上put
 }

2.4 Channel

1. NIO的通道类似于流,但有些区别如下:
 - 通道可以同时进行读写,而流只能读或者只能写
 - 通道可以实现异步读写数据
 - 通道可以从缓冲读数据,也可以写数据到缓冲
2. BIO中的stream是单向的,例如FileInputStream对象只能进行读取数据的操作,而NIO中的通道(Channel)是双向的,可以读操作也可以写操作
3. Channel 在 NIO 中是一个接口public interface Channel extends Closeable{}
4. 常用的Channel类有:FileChannel、DatagramChannel,ServerSocketChannel和SocketChannel【ServerSocketChannel类似ServerSocket,SocketChannel类似Socket】
5. FileChannel用于文件的数据读写,DatagramChannel用于UDP的数据读写, ServerSocketChannel和SocketChannel用于TCP的数据读写

 2.4.1 FileChannel

FileChannel主要用来对本地文件进行 IO 操作,常见的方法有

public int read(ByteBuffer dst)  //从通道读取数据并放到缓冲区中
public int write(ByteBuffer src)  //把缓冲区的数据写到通道中
public long transferFrom(ReadableByteChannel src, long position, long count) //从目标通道中复制数据到当前通道
public long transferTo(long position, long count, WritableByteChannel target) //把数据从当前通道复制给目标通道

channel demo (read%write)代码演示

https://github.com/showkawa/springBoot_2017/blob/master/spb-demo/spb-gateway/src/test/java/com/kawa/spbgateway/service/FileChannelTest.java

package com.kawa.spbgateway.service;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.UUID;


@Slf4j
public class FileChannelTest {
   

   // #1 read @Test public void When_GetDataFromFileChannel_Except_Success() throws IOException { //create the file input stream var file = new File("/home/un/code/springBoot_2017/spb-demo/spb-gateway/src/main/resources/core.yml"); try (var fileInputStream = new FileInputStream(file)) { // get the FileChannel (FileChannelImpl) by FileInputStream var fileChannel = fileInputStream.getChannel(); // create the buffer var byteBuffer = ByteBuffer.allocate((int) file.length()); // read the channel data to buffer fileChannel.read(byteBuffer); log.info("=== core.yml ===: \r\n{}", new String(byteBuffer.array())); } }   
      
   // #2 read and write @Test public void When_OutputData_Except_Success() throws IOException { //create the file input stream var file = new File("/home/un/code/springBoot_2017/spb-demo/spb-gateway/src/main/resources/core.yml"); ByteBuffer outputStr; try (var fileInputStream = new FileInputStream(file)) { // get the FileChannel (FileChannelImpl) by FileInputStream var fileChannel = fileInputStream.getChannel(); // create the buffer outputStr = ByteBuffer.allocate((int) file.length()); // read the channel data to buffer fileChannel.read(outputStr); } // create a file output stream var fileName = UUID.randomUUID().toString().replace("-", ""); try (var fileOutputStream = new FileOutputStream("/home/un/app/test/" + fileName)) { // get file channel by stream var channel = fileOutputStream.getChannel(); outputStr.flip(); channel.write(outputStr); } } }

其中 #1 read的示意图如下

#2 read and write的示意图如下

channel demo (transferFrom)代码演示 

    @Test
    public void When_CopyFileByTransferFrom_Except_Success() throws IOException {
        //create FileInputStream and FileOutputStream
        try (var sourceStream = new FileInputStream("/home/un/code/springBoot_2017/spb-demo/spb-gateway/src/main/resources/core.yml");
             var targetStream = new FileOutputStream("/home/un/app/test/text.txt")) {
            // create the FileChannel
            var sourceCh = sourceStream.getChannel();
            var targetCh = targetStream.getChannel();
            // use transferFrom transfer data to target FileChannel
            targetCh.transferFrom(sourceCh,0 , sourceCh.size());
        }
    }

Buffer和Channel的使用注意事项

1.ByteBuffer 支持类型化的 put 和 get, put 放入的是什么数据类型,get 就应该使用相应的数据类型来取出,否则可能有 BufferUnderflowException 异常。
2. 可以将一个普通 Buffer 转成只读 Buffer,如果向只读Buffer写数据会抛出异常ReadOnlyBufferException

ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();

3. NIO 还提供了 MappedByteBuffer, 可以让文件直接在内存(堆外的内存)中进行修改, 而如何同步到文件由 NIO 来完成.

    @Test
    public void When_ReadDataByMappedByteBuffer_Except_Success() throws IOException {
        File file = new File("/home/un/code/springBoot_2017/spb-demo/spb-gateway/src/main/resources/core.yml");
        long len = file.length();
        byte[] ds = new byte[(int) len];

        MappedByteBuffer mappedByteBuffer = new RandomAccessFile(file, "r")
                .getChannel()
                .map(FileChannel.MapMode.READ_ONLY, 0, len);
        for (int offset = 0; offset < len; offset++) {
            byte b = mappedByteBuffer.get();
            ds[offset] = b;
        }

        Scanner scan = new Scanner(new ByteArrayInputStream(ds)).useDelimiter("\n");
        while (scan.hasNext()) {
            log.info("=== MappedByteBuffer ===: {}", scan.next());
        }

        // try to put
        // java.nio.ReadOnlyBufferException
        mappedByteBuffer.flip();
        mappedByteBuffer.put("brian".getBytes());
    }

4. 前面我们讲的读写操作,都是通过一个Buffer完成的,NIO 还支持通过多个Buffer (即Buffer数组) 完成读写操作

package com.kawa.spbgateway.service;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 *  telnet 127.0.0.1 9988
 */
@Slf4j
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(9988);
        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(10);
        byteBuffers[1] = ByteBuffer.allocate(10);

        SocketChannel sc = serverSocketChannel.accept();

        int msgLength = 20;
        while (true) {
            int byteRead = 0;
            while (byteRead < msgLength) {
                long readL = sc.read(byteBuffers);
                byteRead += readL;
                log.info("=== byteRead ===:{}", byteRead);
                Arrays.stream(byteBuffers).forEach(bu -> {
                    log.info("=== byteRead ===:{ position:{},limit:{} }", bu.position(), bu.limit());
                });
            }

            Arrays.stream(byteBuffers).forEach(buffer -> buffer.flip());

            long byteWrite = 0;
            while (byteWrite < msgLength) {
                long writeL = sc.write(byteBuffers);
                byteWrite += writeL;
            }
            StringBuffer msg = new StringBuffer();
            Arrays.stream(byteBuffers).forEach(bu -> {
                msg.append(new String(bu.array()));
            });
            log.info("=== byteWrite current msg ===: {}", msg);
            Arrays.stream(byteBuffers).forEach(bu -> bu.clear());
            log.info(">>>>>>>>>> byteRead:{}, byteWrite:{},msgLength:{}", byteRead, byteWrite, msgLength);
        }
    }
}

2.5 Selector

1. Java的NIO用非阻塞的IO方式。可以用一个线程,处理多个的客户端连接,就会使用到Selector(选择器)
2. Selector能够检测多个注册的通道上是否有事件发生(注意:多个Channel以事件的方式可以注册到同一个Selector),如果有事件发生,便获取事件然后针每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道,也就是管理多个连接和请求
3. 只有在 连接/通道 真正有读写事件发生时,才会进行读写,就大大地减少了系统开销,并且不必为每个连接都创建一个线程,不用去维护多个线程
4. 避免了多线程之间的上下文切换导致的开销

 2.5.1 Selector示意图

 

1. Netty的IO线程NioEventLoop聚合了Selector(选择器,也叫多路复用器),可以同时并发处理成百上千个客户端连接
2. 当线程从某客户端 Socket 通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务
3. 线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作,所以单独的线程可以管理多个输入和输出通道
4. 由于读写操作都是非阻塞的,这就可以充分提升 IO 线程的运行效率,避免由于频繁 I/O 阻塞导致的线程挂起
5. 一个 I/O 线程可以并发处理 N 个客户端连接和读写操作,这从根本上解决了传统同步阻塞 I/O 一连接一线程模型,架构的性能、弹性伸缩能力和可靠性都得到了极大的提升

2.5.2 Selector类相关方法

public abstract class Selector implements Closeable {

   // 得到一个Selector对象 public static Selector open() throws IOException { return SelectorProvider.provider().openSelector(); }
// 是否是open状态,如果调用了close()方法则会返回false public abstract boolean isOpen();
// 获取当前Selector的Provider public abstract SelectorProvider provider();
// 获取当前channel注册在Selector上所有的key public abstract Set keys();
// 从内部集合得到所有的SelectionKey -> 当前channel就绪的事件列表 public abstract Set selectedKeys();   
// 获取当前是否有事件就绪,该方法立即返回结果,不会阻塞;如果返回值>0,则代表存在一个或多个 public abstract int selectNow() throws IOException;
   // selectNow的阻塞超时方法,超时时间内,有事件就绪时才会返回;否则超过时间也会返回 public abstract int select(long timeout) throws IOException;   
// selectNow的阻塞方法,直到有事件就绪时才会返回 public abstract int select() throws IOException; // 唤醒Selector -> 调用该方法会时,阻塞在select()处的线程会立马返回;即使当前不存在线程阻塞在select()处,
     那么下一个执行select()方法的线程也会立即返回结果,相当于执行了一次selectNow()方法 public abstract Selector wakeup(); // 用完Selector后调用其close()方法会关闭该Selector,且使注册到该Selector上的所有SelectionKey实例无效。channel本身并不会关闭 public abstract void close() throws IOException; }

2.5.3 Selector原理图

NIO非阻塞网络编程相关的(Selector、SelectionKey、ServerScoketChannel 和 SocketChannel) 关系梳理图

1. 当客户端连接时,会通过ServerSocketChannel得到SocketChannel
2. Selector进行监听select 方法, 返回有事件发生的通道的个数.
3. 将socketChannel注册到Selector上, register(Selector sel, int ops), 一个selector上可以注册多个SocketChannel
4. 注册后返回一个SelectionKey, 会和该 Selector 关联(集合)
5. 进一步得到各个 electionKey (有事件发生)
6. 通过SelectionKey反向获取SocketChannel , 方法channel()
7. 可以通过得到的 channel完成业务处理

2.5.3 Selector Demo1 

服务器端接受多个客户端的消息并且打印

Server Code

package com.kawa.spbgateway.service;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;


@Slf4j
public class NioServerTest {

    public static void main(String[] args) throws IOException {
        // 1. create ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 2. create Selector
        Selector selector = Selector.open();
        // 3. ServerSocketChannel  bind and listen port 9998
        ssc.socket().bind(new InetSocketAddress(9998));
        // 4. set the mode non-blocking
        ssc.configureBlocking(false);
        // 5. register the ServerSocketChannel to Selector with event "OP_ACCEPT"
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        // 6. waiting the client SocketChannel connect
        while (true) {
            // get the SelectionKey and the related event
            selector.select();
            Iterator sks = selector.selectedKeys().iterator();
            while (sks.hasNext()) {
                // get the SelectionKey
                SelectionKey sk = sks.next();
                // remove the SelectionKey avoid repeat handle the key
                sks.remove();
                // handle OP_ACCEPT event
                if (sk.isAcceptable()) {
                    try {
                        SocketChannel socketChannel = ssc.accept();
                        log.info(">>>>>>>>>> connected client:{}", socketChannel.getRemoteAddress());
                        socketChannel.configureBlocking(false);
                        // register a OP_READ event to current channel
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // handle OP_READ event
                if (sk.isReadable()) {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    SocketChannel channel = (SocketChannel) sk.channel();
                    try {
                        channel.read(buffer);
                        String msg = new String(buffer.array()).trim();
                        log.info("===== get msg from {} >> {}", channel.getRemoteAddress(), msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }
}

Client Code

package com.kawa.spbgateway.service;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.UUID;

@Slf4j
public class NioClientTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        //1. get a SocketChannel
        SocketChannel sc = SocketChannel.open();
        //2. set non-blocking mode
        sc.configureBlocking(false);
        //3. set connect server address and port
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 9998);
        //4. connect server
        if (!sc.connect(inetSocketAddress)) {
            while (!sc.finishConnect()) {
                log.info(">>>>>>>> connecting to server");
            }
        }
        //5. send msg
        while (true) {
            log.info(">>>>>>>> send mag to server");
            String msg = UUID.randomUUID().toString();
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            sc.write(buffer);
            Thread.sleep(5000);
        }


    }
}

Test result

2.5.4 SelectionKey

SelectionKey,表示 Selector 和网络通道的注册关系, 共四种:

int OP_READ: 代表读操作,值为 1
int OP_WRITE: 代表写操作,值为 4
int OP_CONNECT:代表连接已经建立,值为 8
int OP_ACCEPT: 有新的网络连接可以 accept,值为 16

public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;

相关方法

Object  attach(Object ob)      将给定的对象附加到此键
Object  attachment()           获取当前的附加对象
abstract  void cancel()        请求取消此键的通道到其选择器的注册
abstract  SelectableChannel  channel()     返回为之创建此键的通道
abstract  int interestOps()     获取此键的interest集合
abstract  SelectionKey interestOps(int ops)     将此键的 interest 集合设置为给定值
boolean  isAcceptable()        测试此键的通道是否已准备好接受新的套接字连接
boolean  isConnectable()       测试此键的通道是否已完成其套接字连接操作
boolean  isReadable()          测试此键的通道是否已准备好进行读取
abstract  boolean  isValid()   告知此键是否有效
boolean  isWritable()          测试此键的通道是否已准备好进行写入
abstract  int  readyOps()      获取此键的ready操作集合
abstract  Selector  selector() 返回为此选择器创建的键

 关于方法的详细说明可参考:https://www.apiref.com/java11-zh/java.base/java/nio/channels/SelectionKey.html

2.5.5 ServerSocketChannel

ServerSocketChannel 在服务器端监听新的客户端 Socket 连接,相关方法如下:

abstract SocketChannel  accept()    接受与此通道套接字的连接
ServerSocketChannel  bind(SocketAddress local)    将通道的套接字绑定到本地地址并配置套接字以侦听连接
abstract ServerSocketChannel  bind(SocketAddress local, int backlog)    将通道的套接字绑定到本地地址并配置套接字以侦听连接
abstract SocketAddress  getLocalAddress()    返回此通道的套接字绑定的套接字地址
static ServerSocketChannel  open()    打开服务器套接字通道
abstract  ServerSocketChannel  setOption(SocketOption name, T value)    设置套接字选项的值
abstract ServerSocket  socket()    检索与此通道关联的服务器套接字
int  validOps()    返回标识此通道支持的操作的操作集

关于方法的详细说明可参考:https://www.apiref.com/java11-zh/java.base/java/nio/channels/ServerSocketChannel.html

2.5.6 SocketChannel

SocketChannel,网络 IO 通道,具体负责进行读写操作。NIO 把缓冲区的数据写入通道,或者把通道里的数据读到缓冲区,相关方法如下:

abstract SocketChannel  bind(SocketAddress local)    将通道的套接字绑定到本地地址
abstract boolean  connect(SocketAddress remote)    连接此通道的插座
abstract boolean  finishConnect()     完成连接套接字通道的过程
abstract SocketAddress  getLocalAddress()    返回此通道的套接字绑定的套接字地址
abstract SocketAddress  getRemoteAddress()    返回此通道的套接字连接的远程地址
abstract boolean  isConnected()    判断此通道的网络插座是否已连接
abstract boolean  isConnectionPending()     判断此通道上的连接操作是否正在进行中
static SocketChannel  open()    打开套接字通道
static SocketChannel  open(SocketAddress remote)    打开套接字通道并将其连接到远程地址
abstract int  read(ByteBuffer dst)    从该通道读取一个字节序列到给定的缓冲区
long  read(ByteBuffer[] dsts)    从该通道读取一系列字节到给定的缓冲区
abstract long  read(ByteBuffer[] dsts, int offset, int length)    从该通道读取一系列字节到给定缓冲区的子序列
abstract  SocketChannel  setOption(SocketOption name, T value)    设置套接字选项的值
abstract SocketChannel  shutdownInput()    在不关闭通道的情况下关闭连接以进行读取
abstract SocketChannel  shutdownOutput()    在不关闭通道的情况下关闭连接以进行写入
abstract Socket  socket()    检索与此通道关联的套接字
int  validOps()    返回标识此通道支持的操作的操作集
abstract int  write(ByteBuffer src)    从给定缓冲区向该通道写入一个字节序列
long  write(ByteBuffer[] srcs)    从给定的缓冲区向该通道写入一个字节序列
abstract long  write(ByteBuffer[] srcs, int offset, int length)    从给定缓冲区的子序列向该通道写入一个字节序列

关于方法的详细说明可参考:https://www.apiref.com/java11-zh/java.base/java/nio/channels/SocketChannel.html

2.5.7 Selector Demo2

 服务器端和客户端之间的数据简单聊天通讯

Server Code

package com.kawa.spbgateway.service;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

@Slf4j
public class ChatServerTest {
    private Selector selector;
    private ServerSocketChannel listenChannel;

    public ChatServerTest() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(9999));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        while (true) {
            try {
                int event = selector.select();
                if (event > 0) {
                    Iterator<SelectionKey> sks = selector.selectedKeys().iterator();
                    while (sks.hasNext()) {
                        SelectionKey sk = sks.next();
                        if (sk.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            // when acceptable, register OP_READ event
                            sc.register(selector, SelectionKey.OP_READ);
                            log.info("online -> {}", sc.getRemoteAddress());
                        }
                        if (sk.isReadable()) {
                            reaData(sk);
                        }
                        // avoid repeat handle
                        sks.remove();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void reaData(SelectionKey sk) {
        SocketChannel channel = (SocketChannel) sk.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            int readLength = channel.read(buffer);
            if (readLength > 0) {
                String msg = channel.getRemoteAddress() +" -> " +new String(buffer.array()).trim();


                log.info("get msg from {}", msg);
                // send msg to all client
                sendToAllClient(channel, msg);
            }
        } catch (IOException e) {
            try {
                log.info("offline -> {}", channel.getRemoteAddress());
                sk.channel();
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void sendToAllClient(SocketChannel channel, String msg) throws IOException {
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel();

            if (targetChannel instanceof SocketChannel && targetChannel != channel) {
                SocketChannel destination = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                destination.write(buffer);
            }
        }
    }

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


}

Client Code

package com.kawa.spbgateway.service;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

@Slf4j
public class ChatClientTest {
    private Selector selector;
    private SocketChannel socketChannel;
    private String clientName;

    public ChatClientTest() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            clientName = socketChannel.getLocalAddress().toString().substring(1);
            log.info("{} is ready", clientName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMsg(String msg) {
        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getMsg() {
        try {
            int select = selector.select();
            if (select > 0) {
                Iterator<SelectionKey> sks = selector.selectedKeys().iterator();
                while (sks.hasNext()) {
                    SelectionKey key = sks.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        channel.read(buffer);
                        String msg = new String(buffer.array()).trim();
                        log.info("get mag from {}", msg);
                    }
                    sks.remove();
                }

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

    public static void main(String[] args) {
        ChatClientTest chatClientTest = new ChatClientTest();
        new Thread(() -> {
            while (true) {
                chatClientTest.getMsg();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // Send msg
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine().trim();
            chatClientTest.sendMsg(msg);

        }

    }
}

测试result

 

4. Java的AIO

1. JDK7引入了Asynchronous I/O,即AIO。在进行I/O 编程中,常用到两种模式: Reactor和Proactor。 Java的NIO就是Reactor,当有事件触发时,
服务器端得到通知,进行相应的处理 2. AIO即NIO2.0,叫做异步不阻塞的IO。AIO引入异步通道的概念,采用了Proactor模式,简化了程序编写,有效的请求才启动线程,
它的特点是先由操作系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较多且连接时间较长的应用 3. 目前NIO的代表框架是Netty, AIO的代表框架是smart-socket

简单的demo

package com.kawa.spbgateway.service;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

@Slf4j
public class AioServerTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        // init the server socket channel and listen port 10000
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(10000));

        serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @SneakyThrows
            @Override
            public void completed(AsynchronousSocketChannel client, Void attachment) {
                serverSocketChannel.accept(null, this);
                log.info(">>>>> connect from :{}", client.getRemoteAddress().toString());
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                client.read(buffer, buffer, new CompletionHandler<>() {
                    @SneakyThrows
                    @Override
                    public void completed(Integer index, ByteBuffer buffer) {
                        buffer.flip();
                        log.info(">>>>> get message: {}", new String(buffer.array()).trim());
                        client.close();
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        log.info(">>>>> get message exception: {}", exc.getMessage());
                    }
                });
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                log.info(">>>>> accept channel exception: {}", exc.getMessage());
            }
        });


        // to keep the process not stop
        Thread.currentThread().join();
    }
}

telnet连接测试

 

标签:BIO,java,NIO,abstract,AIO,线程,ByteBuffer,import,public
来源: https://www.cnblogs.com/hlkawa/p/15047212.html

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

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

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

ICode9版权所有