請教一個關於NIO執行方式的問題

wy123456789發表於2004-03-01
用一般的DatagramSocket監聽埠上的訊息用如下程式碼
while(isRun){

receiverByte=new byte[Global.DATAGRAM_BYTES];
receiverDatagramPacket=new DatagramPacket
(receiverByte,receiverByte.length);

try{
1: receiverDatagramSocket.receive(receiverDatagramPacket);
}catch(IOException ex){
ex.printStackTrace();
}
//do something for packet
}

此種方法在1:處會阻塞

使用NIO的程式碼

DatagramChannel dc = DatagramChannel.open() ;
dc.configureBlocking( false ) ;
InetSocketAddress address = new InetSocketAddress( InetAddress.
getLocalHost() , 9000 ) ;

DatagramSocket s = dc.socket() ;
s.bind( address ) ;

Selector select = Selector.open() ;
SelectionKey key = dc.register( select , SelectionKey.OP_READ ) ;

ByteBuffer cb = ByteBuffer.allocate( 100 ) ;

while(true){
cb.clear() ;

int num = select.select() ; 2:

Set selectedKeys = select.selectedKeys() ;
Iterator it = selectedKeys.iterator() ;


while( it.hasNext() ){
SelectionKey k = ( SelectionKey )it.next() ;
if( ( k.readyOps() & SelectionKey.OP_READ )
== SelectionKey.OP_READ ){
DatagramChannel cc = ( DatagramChannel )k.channel() ;
cc.receive( cb ) ;
System.out.println( new String( cb.array() ) ) ;
}
}
}

此方法在2:處阻塞,仍然使用無限迴圈監聽埠,這樣與一般方法不就是一樣了嗎?
NIO的中斷 方式不就沒什麼意義了麼?怎樣以次來提高效能呢?

2者本質上有何區別

相關文章