日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Nio中Buffer的Scattering和Gathering

作者:gacellk 更新時間: 2022-07-18 編程語言
* 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一個一個的倒出來,拼成一句完整的信息

原文鏈接:https://blog.csdn.net/gacellk/article/details/125836330

欄目分類
最近更新