今天一个东西需要用到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
时间: 2024-11-09 00:33:33