Java Nio核心概念理解
SelectionKey:A token representing the registration of a SelectableChannel with a Selector。A selection key is created each time a channel is registered with a selector。
A selection key is created each time a channel is registered with a selector。 A key remains valid until it is cancelled by invoking its cancel method, by closing its channel, or by closing its selector。 Cancelling a key does not immediately remove it from its selector; it is instead added to the selector’s ancelled-key set for removal during the next selection operation。The validity of a key may be tested by invoking isValid method。
SelectionKey包含两种operation sets:interest set & ready set。
- Interest set:兴趣集,表示已注册的事件集合,下一次调用方法,将测试是否有此事件的加入。通过SelectionKey的 int interestOps() 方法,可以获取当前 SelectionKey的感兴趣事件。
- Ready set:准备集,表示已准备就绪的事件集合。通过SelectionKey的 int readyOps()方法,可以获取当前 SelectionKey的准备就绪事件。
Nio中 SocketChannel 如果设置为非阻塞方式,在其发起connect连接事件后返回的永远为false,必须显式调用finishConnect来判断连接是否成功建立。相反,如果 SocketChannel 设置为阻塞方式,则connect方法会根据连接情况返回true or false。
SocketChannel 执行connect事件之后,此时连接处于pending(待定)状态,只有显式调用finishConnect之后则连接更新为CONNECTED状态。否则出现异常NotYetConnectedException。
客户端异常关闭(直接中断idea进程),会导致服务器端一直不断收到客户端的OP_READ事件,即selector.select()
会直接通过,并且是可读状态,但是实际上读到的数据是空的。
由于底层epoll机制的问题,导致select方法可能会一直返回0,造成无限循环的情况。