Java中channel用法總結
本文實例總結了Java中channel用法。分享給大家供大家參考。具體分析如下:
1.Channel接口的定義:
public interface Channel
{
public boolean isOpen( );
public void close( ) throws IOException;
}
2.Channel的常見類型:
FileChannel, SocketChannel, ServerSocketChannel, and DatagramChannel;
FileChannel通過RandomAccessFile, FileInputStream, FileOutputStream的getChannel()來初始化。
SocketChannel sc = SocketChannel.open();
sc.connect (new InetSocketAddress ("somehost", someport));
ServerSocketChannel ssc = ServerSocketChannel.open( );
ssc.socket().bind (new InetSocketAddress (somelocalport));
DatagramChannel dc = DatagramChannel.open();
3.Scatter/Gather,必須使用ByteBuffer.allocateDirect(100)
public interface ScatteringByteChannel extends ReadableByteChannel {
public long read (ByteBuffer [] dsts) throws IOException;
public long read (ByteBuffer [] dsts, int offset, int length) throws IOException;
}
public interface GatheringByteChannel extends WritableByteChannel {
public long write(ByteBuffer[] srcs) throws IOException;
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
}
4.file lock是和file相關,而不是channel??梢詫M程有效,而不是線程??梢酝ㄟ^內存映射文件(memory-mapped file)來實現(xiàn)線程同步
5.buffer = fileChannel.map (FileChannel.MapMode.READ_ONLY, 100, 200);
6.MappedByteBuffer are direct. load( )將整個文件加載到內存(改方法不能保證完成)。force( )將數(shù)據(jù)flush到硬盤。
7.未綁定端口的DatagramChannel系統(tǒng)會自動分配端口。DatagramChannel的connect(),將保證只接受指定源地址的數(shù)據(jù)包。這時候,可以使用普通的read和write方法,包括Scatter/Gather
希望本文所述對大家的java程序設計有所幫助。
相關文章
詳解SpringBoot修改啟動端口server.port的四種方式
這篇文章主要介紹了詳解SpringBoot修改啟動端口server.port的四種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07
Mybatis實現(xiàn)數(shù)據(jù)的增刪改查實例(CRUD)
本篇文章主要介紹了Mybatis實現(xiàn)數(shù)據(jù)的增刪改查實例(CRUD),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
使用Lombok導致打印的tostring中缺少父類的屬性問題
使用Lombok時,若發(fā)現(xiàn)@Data注解的@ToString不包含父類屬性,可通過添加@ToString(callSuper=true)解決,此方法確保在生成toString()時包括父類的屬性,有效解決只打印子類屬性的問題,這種做法對于需要完整信息展示的場景尤為重要2024-11-11
SpringBoot實現(xiàn)過濾器、攔截器與切片的實現(xiàn)和區(qū)別
本文詳細介紹了使用過濾器、攔截器與切片實現(xiàn)每個請求耗時的統(tǒng)計,并比較三者的區(qū)別與聯(lián)系,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02

