聚集(Gather)寫入通道時將多個緩沖區的數據寫入同一個通道,通道將多個緩沖區數據“聚集”到一起;
scatter / gather經常用于需要將傳輸的數據分開處理的場合,例如傳輸一個由消息頭和消息體組成的消息,你可能會將消息體和消息頭分散到不同的buffer中,這樣你可以方便的處理消息頭和消息體。
注意buffer首先被插入到數組,然后再將數組作為channel.read() 的輸入參數。read()方法按照buffer在數組中的順序將從channel中讀取的數據寫入到buffer,當一個buffer被寫滿后,channel緊接著向另一個buffer中寫。
支持分散讀取的通道需要繼承實現ScatteringByteChannel接口:
public interface ScatteringByteChannel extends ReadableByteChannel{ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException; public long read(ByteBuffer[] dsts) throws IOException;}Gathering Writes
Gathering Writes是指數據從多個buffer寫入到同一個channel。如下圖描述:
buffers數組是write()方法的入參,write()方法會按照buffer在數組中的順序,將數據寫入到channel,注意只有position和limit之間的數據才會被寫入。因此,如果一個buffer的容量為128byte,但是僅僅包含58byte的數據,那么這58byte的數據將被寫入到channel中。因此與Scattering Reads相反,Gathering Writes能較好的處理動態消息。
支持聚集寫入的通道需要繼承實現GatheringByteChannel接口:
public interface GatheringByteChannel extends WritableByteChannel{ public long write(ByteBuffer[] srcs, int offset, int length) throws IOException; public long write(ByteBuffer[] srcs) throws IOException;}
|
新聞熱點
疑難解答