Java中的NIO详解Day04-Scatter和Gather

Scatter和Gather

  • Java NIO支持ScatterGather
  • ScatterGather用于描述从Channel中读取或者写入到Channel中的操作
  • ScatterGather经常用于需要将传输的数据分开处理的场合:
    • 传输一个由消息头和消息体组成的消息,需要将消息体和消息头分散到不同的Buffer中,这样可以方便地处理消息头和消息体

Scatter

  • 分散Scatter从Channel中读取: 指在读操作时,将读取的数据写入多个buffer
  • Channel将从Channel中读取的数据分散Scatter到多个Buffer

Gather

  • 聚集Gather写入Channel: 指在写操作时,将多个Buffer数据写入到同一个Channel
  • Channel将多个Buffer中的数据聚集Gather后发送到Channel

Scattering Reads

  • Scattering Reads是指数据从一个Channel读取到多个Buffer
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body = ByteBuffer.allocate(1024);
ByteBuffer[] bufferArray = {header, body};
channel.read(bufferArray);
  • buffer首先被插入到数组中,然后再将数组作为channel.read() 的输入参数
  • read() 方法按照buffer在数组中的顺序将从channel读取的数据写入到buffer
  • 当一个buffer被写满后 ,channel紧接着向另一个buffer中写

Scattering Reader在移动到下一个buffer前,必须填满当前的buffer.所以不适用于消息大小不固定的动态消息.也就是说,如果存在消息头和消息体,消息头必须完成填充,Scattering Reads才能正常工作

Gathering Writes

  • Gathering Writes是指数据从多个buffer写入到同一个channel
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body = ByteBuffer.allocate(1024);
ByteBuffer[] byteArray = {header, body};
channel.write(byteArray);
  • buffer数组是write() 方法的入参
  • write() 方法会按照buffer在数组中的顺序,将数据写入到channel. 只有positionlimit之间的数据才会被写入

如果一个buffer的容量为128字节,但是仅仅包含58字节的数据,那么这58字节的数据将被写入到channel中.因此,Gathering Writes能较好的处理动态消息

猜你喜欢

转载自blog.csdn.net/JewaveOxford/article/details/107537545
今日推荐