Netty学习笔记(一)

  • Netty是由 JBOSS 提供的一个 Java 开源框架,现为 Github 上的独立项目。
  • Netty 是一个异步的、基于事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络 IO 程序。
  • Netty 主要针对在 TCP 协议下,面向 Client 端的高并发应用,或者 Peer-to-Peer 场景下的大量数据持续传输的应用。
  • Netty 本质是一个 NIO 框架,适用于服务器通讯相关的多种应用场景。
  • 典型的应用有:①阿里分布式服务框架 Dubbo 的 RPC 框 架使用 Dubbo 协议进行节点间通信,Dubbo 协议默认使用 Netty 作为基础通信组件,用于实现各进程节点之间的内部通信。②经典的 Hadoop 的高性能通信和序列化组件 Avro 的 RPC 框架,默认采用 Netty 进行跨界点通信。它的 NettyService 基于 Netty 框架二次封装实现。
  • I/O 模型简单的理解:就是用什么样的通道进行数据的发送和接收,很大程度上决定了程序通信的性能。
  • Java 共支持 3 种网络编程模型 I/O 模式:BIONIOAIO
  • Java BIO同步并阻塞(传统阻塞型),服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情就会造成不必要的线程开销。
Java BIO
  • Java NIO同步非阻塞,服务器实现模式为一个线程处理多个请求(连接),即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有 I/O 请求就进行处理。
  • Java AIO(NIO.2)异步非阻塞,AIO 引入异步通道的概念,采用了 Proactor模式,简化了程序编写,有效的请求才启动线程,它的特点是先由操作系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较多且连接时间较长的应用。
  • BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4 以前的唯一选择,但程序简单易理解。
  • NIO方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,弹幕系统,服务器间通讯等。编程比较复杂,JDK1.4 开始支持。
  • AIO方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调用 OS 参与并发操作,编程比较复杂,JDK7 开始支持。
  • Java BIO就是传统的Java I/O编程,其相关的类和接口在java.io
  • BIO(BlockingI/O)同步阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情就会造成不必要的线程开销,可以通过线程池机制改善(实现多个客户连接服务器)。
  • Java BIO 编程流程的梳理:
    • 服务器端启动一个 ServerSocket;
    • 客户端启动 Socket 对服务器进行通信,默认情况下服务器端需要对每个客户建立一个线程与之通讯;
    • 客户端发出请求后,先咨询服务器是否有线程响应,若没有则等待,或者被拒绝;
    • 若有响应,则客户端线程会等待请求结束后,再继续执行。
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BIOServer {
    public static void main(String[] args) throws Exception {
        //采用线程池机制
        //思路:
        //1、创建一个线程池
        //2、如果有客户端连接,就创建一个线程,与之通讯(单独写一个方法)
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了...");
        while (true) {
            System.out.println("线程信息id=" + Thread.currentThread().getId() + ",名字=" + Thread.currentThread().getName());
            //监听,等待客户端连接
            System.out.println("等待连接....");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端...");
            //就创建一个线程,与之通讯(单独写一个方法)
            newCachedThreadPool.execute(new Runnable() {
                public void run() {
                    //可以和客户端通讯
                    handler(socket);
                }
            });
        }
    }
    //编写一个handler方法,和客户端通讯
    public static void handler(Socket socket) {
        try {
            System.out.println("线程信息id=" + Thread.currentThread().getId() + ",名字=" + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            //通过socket获取输入流
            InputStream inputStream = socket.getInputStream();
            //循环的读取客户端发送的数据
            while (true) {
                System.out.println("线程信息id=" + Thread.currentThread().getId() + ",名字=" + Thread.currentThread().getName());
                System.out.println("read....");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    //输出客户端发送的数据
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和client的连接...");
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  • Java BIO问题分析:
    • 每个请求都需要创建独立的线程,与对应的客户端进行数据Read,业务处理和Write数据。
    • 当并发数较大时,需要创建大量线程来处理连接,系统资源占用较大。
    • 连接建立后,若当前线程暂时没有数据可读,则线程就阻塞在 Read 操作上,造成线程资源浪费。
  • Java NIO(Java non-blocking IO):从 JDK1.4 开始,Java 提供了一系列改进的输入/输出的新特性,被统称为 NIO(即 NewIO),是同步非阻塞的。
  • Java NIO相关类都被放在java.nio包及子包下,并且对原java.io包中的很多类进行改写。
  • Java NIO有三大核心部分:Channel(通道)、Buffer(缓冲区)、Selector(选择器)。
  • Java NIO面向缓冲区面向块编程的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络。
  • Java NIO的非阻塞模式,使一个线程从某个通道发送请求或读取数据,但是它仅能得到目前可用的数据,若目前没有数据可用时,则什么都不会获取,而不是保持线程阻塞,所以直至数据变化之前,该线程可以继续做其他的事情。
  • 通俗理解:Java NIO是可以做到用一个线程来处理多个操作的。假设有 10000 个请求过来,根据实际情况,可以分配 50 或者 100 个线程来处理,不像之前的阻塞 IO 那样,非得分配 10000 个。
  • HTTP 2.0使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求的数量比 HTTP 1.1 大了好几个数量级。
import java.nio.IntBuffer;
public class BasicBuffer {
    public static void main(String[] args) {
        //举例说明 Buffer 的使用(简单说明)
        //创建一个 Buffer,大小为 5,即可以存放 5 个 int
        IntBuffer intBuffer = IntBuffer.allocate(5);
        //向buffer存放数据
        for (int i = 0; i < intBuffer.capacity(); i++) {
            intBuffer.put(i * 2);
        }
        //如何从 buffer 读取数据
        //将 buffer 转换,注意读写切换(!!!)
        intBuffer.flip();
        //若缓冲区还有剩余数据,则继续读取
        while (intBuffer.hasRemaining()) {
            System.out.println(intBuffer.get());
        }
    }
}
  • Java NIO与BIO的比较:
    • BIO 以流的方式处理数据,而 NIO 以块的方式处理数据,块 I/O 的效率比流 I/O 高很多。
    • BIO 是阻塞的,NIO 则是非阻塞的。
    • BIO 基于字节流和字符流进行操作,而 NIO 基于 Channel(通道)和 Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。Selector(选择器)用于监听多个通道的事件(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道。
三大核心部分的关系图
  • Selector、Channel和Buffer之间的关系如下:
    • 每个 Channel 都会对应一个 Buffer;
    • Selector 对应一个线程,一个线程对应多个 Channel(连接);
    • 该图反应了有三个 Channel 注册到该 Selector;
    • 程序切换到哪个 Channel 是由事件(Event)决定的;
    • Selector 会根据不同的事件,在各个通道上切换;
    • Buffer 就是一个内存块,底层是有一个数组;
    • 通过 Buffer来读取或写入数据,BIO 中要么是输入流或是输出流,不能双向,但 NIO 的 Buffer 是可读可写的,需要 flip 方法切;
    • Channel 是双向的,可以返回底层操作系统的情况,比如 Linux,底层的操作系统通道就是双向的。
  • 缓冲区(Buffer):本质上是一个可以读写数据的内存块,可以理解成是一个容器对象(含数组),其内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、网络读取数据的渠道,但是必须经过 Buffer才能读取和写入数据。
  • 在 NIO 中,Buffer 是一个顶层父类,它是一个抽象类,类的层级关系图如下所示:
  • Buffer 类定义了所有的缓冲区都具有的四个属性来提供关于其所包含数据元素的信息:
Buffer类相关方法一览
ByteBuffer类
  • Java NIO 的通道类似于流,但有些区别如下:
    • 通道可以同时进行读写,而流只能读或者只能写;
    • 通道可以实现异步读写数据;
    • 通道可以从缓冲区中读数据,也可以写数据到缓冲区中。
  • Java BIO 中的 Stream 是单向的,例如FileInputStream对象只能读数据,而 Java NIO 中的通道(Channel)是双向的,可以进行读写操作。
  • Channel 在 NIO 中是一个接口:public interface Channel extends Closeable{}
  • 常用的 Channel 类有:FileChannelDatagramChannelServerSocketChannelSocketChannel。(ServerSocketChannel类似于ServerSocketSocketChannel类似于Socket
  • FileChannel用于文件的数据读写;DatagramChannel用于UDP的数据读写;ServerSocketChannelSocketChannel用于TCP的数据读写。
  • 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):从当前通道中把数据复制给目标通道中。
  • 写入数据到文件的案例:
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel01 {
    public static void main(String[] args) throws Exception {
        String str = "hello,张三";
        //创建一个输出流 -> channel
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\opt\\file01.txt");
        //通过 fileOutputStream 获取对应的 FileChannel
        //这个 fileChannel 真实类型是 FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();
        //创建一个缓冲区 ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //将 str 放入 byteBuffer
        byteBuffer.put(str.getBytes());
        //对 byteBuffer 进行翻转 flip
        byteBuffer.flip();
        //将 byteBuffer 数据写入到 fileChannel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();
    }
}
  • 读取文件中数据的案例:
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel02 {
    public static void main(String[] args) throws Exception {
        //创建文件的输入流
        File file = new File("D:\\opt\\file01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        //通过 fileInputStream 获取对应的 FileChannel -> 实际类型为 FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();
        //创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
        //将通道的数据读入到 Buffer
        fileChannel.read(byteBuffer);
        //将 byteBuffer 的字节数据转成 String
        System.out.println(new String(byteBuffer.array()));
        fileInputStream.close();
    }
}
  • 使用一个缓冲区完成文件的读取和写入:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:\\opt\\file01.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\opt\\file02.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        //循环读取
        while (true) {
            //这里有一个重要的操作,一定不要忘了
            /*
            public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
            */
            //清空 buffer
            byteBuffer.clear();
            int read = fileChannel01.read(byteBuffer);
            //输出读到的字节数
            System.out.println("read = " + read);
            //表示读完
            if (read == -1) {
                break;
            }
            //将 buffer 中的数据写入到 fileChannel02 -- file02.txt
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }
        //关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}
  • 使用transferFrom方法拷贝文件:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class NIOFileChannel04 {
    public static void main(String[] args) throws Exception {
        //创建相关流
        FileInputStream fileInputStream = new FileInputStream("D:\\opt\\avatar1.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\opt\\avatar2.jpg");
        //获取各个流对应的 FileChannel
        FileChannel srcCh = fileInputStream.getChannel();
        FileChannel destCh = fileOutputStream.getChannel();
        //使用 transferForm 完成拷贝
        destCh.transferFrom(srcCh, 0, srcCh.size());
        //关闭相关通道和流
        srcCh.close();
        destCh.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
  • ByteBuffer 支持类型化的 put 和 get,put 放入的是什么数据类型,get 就应该使用相应的数据类型来取出,否则可能有 BufferUnderflowException 异常。
import java.nio.ByteBuffer;
public class NIOByteBufferPutGet {
    public static void main(String[] args) {
        //创建一个 Buffer
        ByteBuffer buffer = ByteBuffer.allocate(64);
        //类型化方式放入数据
        buffer.putInt(100);
        buffer.putLong(9);
        buffer.putChar('尚');
        buffer.putShort((short) 4);
        //按类型取出对应类型的数据
        buffer.flip();
        System.out.println(buffer.getInt());
        System.out.println(buffer.getLong());
        System.out.println(buffer.getChar());
        System.out.println(buffer.getShort());
    }
}
  • 可以将一个普通 Buffer 转成只读 Buffer:
import java.nio.ByteBuffer;
public class ReadOnlyBuffer {
    public static void main(String[] args) {
        //创建一个 buffer
        ByteBuffer buffer = ByteBuffer.allocate(64);
        for (int i = 0; i < 64; i++) {
            buffer.put((byte) i);
        }
        //读取
        buffer.flip();
        //得到一个只读的 Buffer
        ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
        System.out.println(readOnlyBuffer.getClass());
        //读取
        while (readOnlyBuffer.hasRemaining()) {
            System.out.println(readOnlyBuffer.get());
        }
        //不能往只读的缓冲区中再写入数据,否则会出现这个异常:ReadOnlyBufferException
        readOnlyBuffer.put((byte) 100);
    }
}
  • NIO 还提供了 MappedByteBuffer,可以让文件直接在内存(堆外的内存)中进行修改,而如何同步到文件由 NIO 来完成。
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
 * 说明 MappedByteBuffer 可让文件直接在内存(堆外内存)修改,操作系统不需要拷贝一次
 */
public class MappedByteBufferTest {
    public static void main(String[] args) throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\opt\\file01.txt", "rw");
        //获取对应的文件通道
        FileChannel channel = randomAccessFile.getChannel();
        /**
         * 参数 1:FileChannel.MapMode.READ_WRITE 使用的读写模式
         * 参数 2:0:可以直接修改的起始位置
         * 参数 3:5: 是映射到内存的大小(不是索引位置),即将 file01.txt 的多少个字节映射到内存,表示可以直接修改的数据范围为 0-5 个字节
         * MappedByteBuffer 实际类型为 DirectByteBuffer
         */
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
        mappedByteBuffer.put(0, (byte) 'H');
        mappedByteBuffer.put(3, (byte) '9');
        //越界异常:IndexOutOfBoundsException
        //mappedByteBuffer.put(5, (byte) 'Y');
        randomAccessFile.close();
        System.out.println("修改成功~~~");
    }
}
  • NIO 还支持通过多个 Buffer(即 Buffer数组)完成读写操作,即 Scattering 和 Gathering。
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
/**
 * Scattering:将数据写入到 buffer 时,可以采用 buffer 数组,依次写入 [分散]
 * Gathering:从 buffer 读取数据时,可以采用 buffer 数组,依次读 [聚集]
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws Exception {
        //使用 ServerSocketChannel 和 SocketChannel 网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口到 socket,并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        //创建 buffer 数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        //等客户端连接 (telnet)
        SocketChannel socketChannel = serverSocketChannel.accept();
        //假定从客户端接收 8 个字节
        int messageLength = 8;
        //循环的读取
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {
                long l = socketChannel.read(byteBuffers);
                //累计读取的字节数
                byteRead += l;
                System.out.println("byteRead=" + byteRead);
                //使用流打印,查看当前的这个 buffer 的 position 和 limit
                Arrays.stream(byteBuffers).map(buffer -> "position=" + buffer.position() + ",limit=" + buffer.limit()).forEach(System.out::println);
            }
            //将所有的 buffer 进行 flip
            Arrays.asList(byteBuffers).forEach(Buffer::flip);
            //将数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }
            //将所有的buffer进行clear
            Arrays.asList(byteBuffers).forEach(Buffer::clear);
            System.out.println("byteRead=" + byteRead + ",byteWrite=" + byteWrite + ",messageLength=" + messageLength);
        }
    }
}
  • Java NIO采用非阻塞的 IO 方式,使用Selector(选择器)可以用一个线程处理多个客户端连接。Selector 能够检测多个注册在通道上是否有事件发生(注意:多个 Channel 以事件的方式可以注册到同一个 Selector) 只有在(连接/通道)真正有读写事件发生时,才会进行读写,这就大大地减少了系统开销,不必为每个连接都创建一个线程,即不用去维护多个线程,避免了多线程之间的上下文切换导致的开销。
  • Netty 的 IO 线程 NioEventLoop 聚合了 Selector(选择器,也叫多路复用器),可以并发处理成百上千个客户端连接。当线程从某客户端 Socket 通道进行读写数据时,若没有数据可用时,则该线程可以进行其他任务。线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作,所以单个线程可以管理多个输入和输出通道。由于读写操作都是非阻塞的,这就可以充分提升 IO 线程的运行效率,避免由于频繁 I/O 阻塞导致的线程挂起。
  • 一个 I/O 线程可以并发处理 N 个客户端连接和读写操作,这从根本上解决了传统同步阻塞 I/O 一连接一线程模型,架构的性能、弹性伸缩能力和可靠性都得到了极大的提升。
  • Selector 相关方法说明:
    • selector.select():阻塞;
    • selector.select(1000):阻塞 1000 毫秒,在 1000 毫秒后返回;
    • selector.wakeup():唤醒 selector;
    • selector.selectNow():不阻塞,立马返还。
NIO 非阻塞网络编程关系图
  • 对上图的说明:
    • 当客户端连接时,会通过 ServerSocketChannel 得到 SocketChannel;
    • Selector 进行监听 select 方法,返回有事件发生的通道个数;
    • 将 socketChannel 注册(register(Selector sel, int ops))到 Selector 上,一个 Selector 上可以注册多个 SocketChannel,注册后返回一个 SelectionKey,会和该 Selector 关联(用集合管理),进一步得到各个 SelectionKey(有事件发生),再通过 SelectionKey 反向获取(通过 channel()方法) SocketChannel,最后通过得到的 channel来完成业务处理。
  • 实现服务器和客户端的简单通讯(NIO入门案例):
  • 服务端代码:
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;
import java.util.Set;
public class NIOServer {
    public static void main(String[] args) throws IOException {
        //创建ServerSocketChannel -> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个Selector对象
        Selector selector = Selector.open();
        //绑定一个端口6666
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置通道为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //把 serverSocketChannel 注册到 selector ,关心事件为:OP_ACCEPT,有新的客户端连接
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        while (true) {
            //等待1秒,如果没有事件发生,就返回
            if (selector.select(1000) == 0) {
                System.out.println("服务器等待了1秒,无连接");
                continue;
            }
            //如果返回值大于,表示已经获取到关注的事件,就获取到相关的 selectionKey 集合,反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历 Set<SelectionKey>,使用迭代器遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                //获取到SelectionKey
                SelectionKey key = keyIterator.next();
                //根据 key 对应的通道发生的事件,做相应的处理
                //若是 OP_ACCEPT,则表示有新的客户端连接
                if (key.isAcceptable()) {
                    //该客户端生成一个 SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功,生成了一个SocketChannel:" + socketChannel.hashCode());
                    //将SocketChannel设置为非阻塞模式
                    socketChannel.configureBlocking(false);
                    //将socketChannel注册到selector,关注事件为 OP_READ,同时给SocketChannel关联一个Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    //通过key,反向获取到对应的Channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到该channel关联的Buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端:" + new String(buffer.array()));
                }
                //手动从集合中移除当前的 selectionKey,防止重复操作
                keyIterator.remove();
            }
        }
    }
}
  • 客户端代码:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class NIOClient {
    public static void main(String[] args) throws IOException {
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置通道为非阻塞模式
        socketChannel.configureBlocking(false);
        //提供服务器端的IP和端口
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 6666);
        //连接服务器
        //若连接不成功
        if (!socketChannel.connect(socketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间,客户端不会阻塞,可以做其他工作。。。");
            }
        }
        //如果连接成功,就发送数据
        String str = "hello, 张三";
        //包裹字节数组,分配缓冲区的容量由消息的长度决定
        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
        //发送数据,实际上就是将buffer数据写入到channel
        socketChannel.write(byteBuffer);
        System.in.read();
    }
}
  • SelectionKey,表示 Selector 和网络通道的注册关系,共四种:
    • int OP_READ:代表读操作,值为 1;
    • int OP_WRITE:代表写操作,值为 4;
    • int OP_CONNECT:代表连接已经建立,值为 8;
    • int OP_ACCEPT:有新的网络连接可以 accept,值为 16。
SelectionKey相关方法
  • ServerSocketChannel:在服务器端监听新的客户端 Socket 连接,相关方法如下:
  • SocketChannel:网络 IO 通道,具体负责进行读写操作。NIO 把缓冲区的数据写入通道,或者把通道里的数据读到缓冲区,相关方法如下:
  • NIO网络编程应用实例-群聊系统:
    • 编写一个 NIO 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞),实现多人群聊;
    • 服务器端:可以监测用户上线,离线,并实现消息转发功能;
    • 客户端:通过 Channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)
  • 服务端代码:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class GroupChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;
    //构造器
    //初始化工作
    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置通道为非阻塞模式
            listenChannel.configureBlocking(false);
            //将该 listenChannel 注册到 selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //监听
    public void listen() {
        try {
            //循环处理
            while (true) {
                int count = selector.select();
                //有事件处理
                if (count > 0) {
                    //遍历得到 selectionKey 集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        //取出 selectionKey
                        SelectionKey key = iterator.next();
                        //监听到 accept
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //将该 sc 注册到 selector
                            sc.register(selector, SelectionKey.OP_READ);
                            //提示上线
                            System.out.println(sc.getRemoteAddress() + " 上线 ");
                        }
                        //通道发送read事件,即通道是可读的状态
                        if (key.isReadable()) {
                            // 处理读
                            readData(key);
                        }
                        //当前的 key 删除,防止重复处理
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待....");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //发生异常处理....
        }
    }
    //读取客户端消息
    public void readData(SelectionKey key) {
        SocketChannel channel = null;
        try {
            //得到 channel
            channel = (SocketChannel) key.channel();
            //创建 buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            //根据 count 的值做处理
            if (count > 0) {
                //把缓存区的数据转成字符串
                String msg = new String(buffer.array());
                //输出该消息
                System.out.println("form 客户端:" + msg);
                //向其它的客户端转发消息(除了自己),专门写一个方法来处理
                sendInfoToOtherClients(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
    //转发消息给其它客户(通道)
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
        //遍历所有注册到 selector 上的 SocketChannel,并排除 self
        for (SelectionKey key : selector.keys()) {
            //通过 key 取出对应的 SocketChannel
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                //转型
                SocketChannel dest = (SocketChannel) targetChannel;
                //将 msg 存储到 buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //将 buffer 的数据写入通道
                dest.write(buffer);
            }
        }
    }
    public static void main(String[] args) {
        //创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
  • 客户端代码:
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;
public class GroupChatClient {
    //定义相关的属性
    private final String HOST = "127.0.0.1";//服务器的ip
    private final int PORT = 6667;//服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;
    //构造器,完成初始化工作
    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        //设置通道为非阻塞模式
        socketChannel.configureBlocking(false);
        //将 channel 注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到 username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok...");
    }
    //向服务器发送消息
    public void sendInfo(String info) {
        info = username + " 说:" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //读取从服务器端回复的消息
    public void readInfo() {
        try {
            int readChannels = selector.select();
            //有可以用的通道
            if (readChannels > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        //得到相关的通道
                        SocketChannel sc = (SocketChannel) key.channel();
                        //得到一个 Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        sc.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                //删除当前的 selectionKey,防止重复操作
                iterator.remove();
            } else {
                //System.out.println("没有可以用的通道...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
        //启动我们客户端
        GroupChatClient chatClient = new GroupChatClient();
        //启动一个线程,每隔 3 秒,读取从服务器发送数据
        new Thread(() -> {
            while (true) {
                chatClient.readInfo();
                try {
                    Thread.currentThread().sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        //按行读取内容
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
  • 在 Java 程序中,常用的零拷贝有 mmap(内存映射)和 sendFile。
  • Java 传统 IO 和网络编程的一段代码:
File file = new File("test.txt");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
byte[] arr = new byte[(int) file.length()];
raf.read(arr);
Socket socket = new ServerSocket(8080).accept();
socket.getOutputStream().write(arr);
传统IO模型
  • DMA:direct memory access 直接内存拷贝(不使用 CPU)
  • mmap:通过内存映射,将文件映射到内核缓冲区,并且用户空间可以共享内核空间的数据,这样在进行网络传输时就可以减少内核空间到用户空间的拷贝次数。
mmap
  • Linux2.1 版本提供了sendFile函数,其基本原理为:数据根本不经过用户态,直接从内核缓冲区进入Socket Buffer,由于和用户态完全无关,就减少了一次上下文切换。零拷贝从操作系统角度,是没有 cpu 拷贝
  • Linux在2.4 版本中,做了一些修改,避免了从内核缓冲区拷贝到 Socketbuffer 的操作,直接拷贝到协议栈,又一次减少了数据拷贝。
  • 其实还是有一次 cpu 拷贝(kernel buffer -> socket buffer),但是拷贝的信息很少,比如 length、offset 消耗低,可以忽略。
  • 我们说零拷贝,是从操作系统的角度来说的。因为内核缓冲区之间,没有数据是重复的(只有 kernel buffer 有一份数据)。零拷贝不仅仅带来更少的数据复制,还能带来其它的性能优势,例如更少的上下文切换,更少的 CPU 缓存伪共享以及无 CPU 校验和计算。
  • mmapsendFile的区别:
    • mmap 适合小数据量读写,sendFile 适合大文件传输。
    • mmap 需要 4 次上下文切换,3 次数据拷贝;sendFile 需要 3 次上下文切换,最少 2 次数据拷贝。
    • sendFile 可以利用 DMA 方式,减少 CPU 拷贝,mmap 则不能(必须从内核拷贝到 Socket缓冲区)。
  • Java NIO零拷贝案例:
  • 服务端代码:
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class NewIOServer {
    public static void main(String[] args) throws Exception {
        InetSocketAddress address = new InetSocketAddress(7001);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.bind(address);
        //创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            int readcount = 0;
            while (-1 != readcount) {
                try {
                    readcount = socketChannel.read(byteBuffer);
                } catch (Exception ex) {
                    // ex.printStackTrace();
                    break;
                }
                //倒带:position = 0,mark=-1
                byteBuffer.rewind();
            }
        }
    }
}
  • 客户端代码:
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
public class NewIOClient {
    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 7001));
        String filename = "D:\\opt\\kafka_2.12-2.5.0.tgz";
        //得到一个文件channel
        FileChannel fileChannel = new FileInputStream(filename).getChannel();
        //准备发送
        long startTime = System.currentTimeMillis();
        //在 linux 下一个 transferTo 方法就可以完成传输
        //在 windows 下一次调用 transferTo 方法只能发送 8m的内容,这就需要分段传输文件,而且要注意传输时的位置
        //transferTo 底层使用到零拷贝
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
        System.out.println("发送的总的字节数=" + transferCount + " 耗时: " + (System.currentTimeMillis() - startTime));
        //关闭通道
        fileChannel.close();
    }
}
  • JDK7 引入了AsynchronousI/O,即AIO。在进行 I/O 编程中,常用到两种模式:ReactorProactor。Java 的 NIO 就是 Reactor,当有事件触发时,服务器端得到通知,进行相应的处理。
  • AIO(NIO2.0):异步不阻塞的 IO。AIO 引入异步通道的概念,采用了 Proactor 模式,简化了程序编写,有效的请求才启动线程,它的特点是先由操作系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较多且连接时间较长的应用。
BIO NIO AIO
IO模型 同步阻塞 同步非阻塞(多路复用) 异步非阻塞
编程难道 简单 复杂 复杂
可靠性
吞吐量
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容