NIO概念
NIO是新IO,與老IO相比,老IO是通過(guò)STREAM來(lái)發(fā)送CHARACTER,新IO是通過(guò)CHANNL 發(fā)送BUFFER;老IO對(duì)于多條鏈接需要啟動(dòng)多個(gè)線程處理,新IO只需一條線程即可處理多條鏈接;新IO是事件驅(qū)動(dòng)。客戶(hù)端,非SELECTOR模式:
//打開(kāi)一個(gè)CHANNEL
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://google.com", 80));
//等待可寫(xiě)狀態(tài)
while(! socketChannel.finishConnect() ){
//wait, or do something else
}
//寫(xiě)資料
socketChannel.write(buf);
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://google.com", 80));
//等待可寫(xiě)狀態(tài)
while(! socketChannel.finishConnect() ){
//wait, or do something else

}
//寫(xiě)資料
socketChannel.write(buf);
客戶(hù)端,SELECTOR模式:
//打開(kāi)一個(gè)CHANNEL
SocketChannel channel = SocketChannel.open();
//新建一個(gè)SELECTOR
Selector selector = Selector.open();
channel.configureBlocking(false);
//將SELECTOR注冊(cè)到CHANNEL中
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
while(true) {
//查詢(xún)可用狀態(tài)
int readyChannels = selector.select();
//狀態(tài)不可用
if(readyChannels == 0) continue;
}
//狀態(tài)可用
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
//提交所需處理的代碼
}
//移除所有KEY
keyIterator.remove();
}
SocketChannel channel = SocketChannel.open();
//新建一個(gè)SELECTOR
Selector selector = Selector.open();
channel.configureBlocking(false);
//將SELECTOR注冊(cè)到CHANNEL中
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
while(true) {
//查詢(xún)可用狀態(tài)
int readyChannels = selector.select();
//狀態(tài)不可用
if(readyChannels == 0) continue;
}
//狀態(tài)可用
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
//提交所需處理的代碼
}
//移除所有KEY
keyIterator.remove();
}
posted on 2013-07-16 12:31 paulwong 閱讀(356) 評(píng)論(0) 編輯 收藏 所屬分類(lèi): J2SE 、性能優(yōu)化