Java NIO 在網路編程中的應用

來源:互聯網
上載者:User

   事實上Java nio引入了非同步機制,非同步I/O 在Linux上有 select poll epoll,支援多工。在Java裡就是通過nio的一整套類來實現的,主要有:

ByteBuffer

SocketChannel

ServerSocketChannel

Selector

SelectionKey

 

註冊:

    channel調用 register來向selector註冊,

移除:

    SelectionKey.cancel //僅僅把selectionkey 對應的channel從selector中移除,socket仍然處於活動狀態,需要手動關閉。

    channel.close()//從selector移除,加關閉channel關聯的socket對象

 

 

//得到一個selector

Selector select = Selector.open();

ServerSocketChannel ss = ServerSocketChannel.open(); 

//必須配置成non-blocking

ss.configureBlocking(false);

//綁定到一個地址

ss.socket().bind( new InetSocketAddress("0.0.0.0", 5858));

 

//把channel註冊selector,此時會有一個SelectionKey跟這個channel關聯

//當有串連進來時,select可以返回selectedKeys

ss.register(select, SelectionKey.OP_ACCEPT);

 

 

 

while(select.select() >= 0){

//返回處於就緒狀態的keys

Set<SelectionKey> keyReady = select.selectedKeys();

 

//輪詢每一個就緒狀態的key,通過key可以得到channel,也可以通過key從selector裡刪除

for( Iterator<SelectionKey> iter = keyReady.iterator(); iter.hasNext(); ){

SelectionKey sk = iter.next();

iter.remove();

 

System.out.println("cancel" + select.keys().size());

 

SocketChannel client = null;

if ( sk.channel() instanceof ServerSocketChannel){

ss= (ServerSocketChannel)sk.channel();

client = ss.accept();

System.out.println("accept: " + client.socket());

//client.socket().close();

//必須配置成non-blocking

client.configureBlocking(false);

//把非被動socket註冊到selector

client.register(select, SelectionKey.OP_READ);

}

else if (sk.channel() instanceof SocketChannel ){

SocketChannel ch = (SocketChannel)sk.channel();

ByteBuffer recvBuf = ByteBuffer.allocate(100);

//必須用nio中的ByteBuffer,否則會出錯

int len = ch.read(recvBuf);

if ( len < 0){

//移除前必須關閉socket,否則會有很多socket處於開啟狀態

ch.socket().close();

//從selector移除channel

sk.cancel();

continue;

}

recvBuf.flip();

   ch.write(recvBuf);

   //sk.cancel();

   System.out.println("cancel" + select.keys().size() + "len " + len);

 

   len = ch.read(recvBuf);

 

//關閉channel,此時會關閉channel對應的socket,同時從selector中移除這個channel

 //  ch.close();

System.out.println("len" + len);

 

}

else{

System.out.println("error change");

}

}

}

 

System.out.println("end======");

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.