今天一个东西需要用到java 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 sks=selector.selectedKeys();
Iterator it = sks.iterator();
while(it.hasNext()){
SelectionKey key=it.next();
if(key.isReadable()){
System.out.println("is Readable() ");
SocketChannel isc=(SocketChannel)key.channel();
isc.read(byteBuffer);
}
it.remove();
}
}
System.out.println("return from select() ");
}
}
关于是否需要it.remove()这一行呢。
按照上面运行的结果:
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在selectedKeys中执行remove操作的话。下一次select()操作将会直接返回,但其返回的值是0。Selector类型于“水平触发”,但与水平触发不一样的是,下一次Selector.select的时候,并不会返回上一次没有remove掉的键集。