* Scattering:将数据写入到buffer时,可以采用buffer数组,依次写入 * Gathering:从buffer读取数据时,可以采用buffer数组,依次读取
示例代码
public static void main(String[] args) throws IOException { //使用serversocketchannel和socketchannel,客户端就用telnet连接 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); InetSocketAddress inetSocketAddress = new InetSocketAddress(8000); //绑定接口到socket,并启动 serverSocketChannel.socket().bind(inetSocketAddress); ByteBuffer[] byteBuffers = new ByteBuffer[2]; byteBuffers[0] = ByteBuffer.allocate(5); byteBuffers[1] = ByteBuffer.allocate(3); //等待客户端连接(telnet) SocketChannel socketChannel = serverSocketChannel.accept(); int messageLength = 8;//假定从客户端接受8个字节 while(true){ int byteRead = 0; while(byteRead< messageLength){ long r = socketChannel.read(byteBuffers); byteRead +=r; System.out.println("byteRead"+byteRead); //使用流打印,看当前buffer的postion和limit Arrays.asList(byteBuffers).stream().map(buffer ->"postion=" +buffer.position()+",limit="+buffer.limit()).forEach(System.out::println); } //将所有的buffer反转 Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip()); //将数据读出显示到客户端 long byteWirte = 0; while(byteWirte<messageLength){ long l = socketChannel.write(byteBuffers); byteWirte+=l; } //将所有的buffer 运行claer Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear()); System.out.println("byteRead:"+byteWirte+"byteWrite"+byteWirte+"messagelength"+messageLength); } }
当使用telnet发送9个byte的数组时
当使用telnet再次发送6个byte的数组时
再次连续发送两次一个byte
由此可以看出Scattering的意思就像buffer数组像水杯一样,将数据(水)倒入数组的第一个buffer,满了的话,就向第二个buffer接着倒,一直到buffer数组都倒满。
而Gathering就是在读取的时候将按顺序,数组里的buffer一个一个的倒出来,拼成一句完整的信息