標籤:
今天一個東西需要用到java nio的東西。在網上查了一下資料,發現有Apache的Mina,Netty等,感覺JDK中帶的NIO有點雞肋啊。之前看過這部分的內容,但好長一段時間沒有用,也就忘得七七八八了。如今是溫故而知新,但其中遇到了些疑問:
先貼上代碼吧:
public static void main(String[] args) throws Exception{Thread sh=new Thread(new Runnable() {public void run(){try{ServerSocket ss=new ServerSocket(3000);Socket client=ss.accept();OutputStream os=client.getOutputStream();while(true){os.write("Helloworld".getBytes());Thread.sleep(1000);}}catch(Exception e){e.printStackTrace();}}});sh.start();SocketChannel sc=SocketChannel.open();sc.socket().connect(new InetSocketAddress("localhost",3000) );sc.configureBlocking(false);Selector selector=Selector.open();sc.register(selector,SelectionKey.OP_READ);ByteBuffer byteBuffer=ByteBuffer.allocate(1000);while(true){if(selector.select()>0){Set<SelectionKey> sks=selector.selectedKeys();for(SelectionKey key:sks){if(key.isReadable()){System.out.println("is Readable() ");SocketChannel isc=(SocketChannel)key.channel();isc.read(byteBuffer);}sks.remove(key);}}System.out.println("return from select() ");}}
關於是否需要sks.remove(key)這一行呢。
按照上面啟動並執行結果:
is Readable() return from select() is Readable() return from select() is Readable() return from select() is Readable() return from select()
然後把sks.remove(key)這一行注釋掉,再次運行:
is Readable()return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() return from select() ...
說明了,如果不對已經處理完的SelectionKey在selectedKyes中執行remove操作的話。下一次select()操作將會直接返回,但其返回的值是0
JAVA NIO中selectedKeys返回的鍵集,對其中的SelectionKey執行操作之後,是否需要在selectedKeys()中對其執行remove 操作