我有一个带有主循环的简单非阻塞服务器:
try {
while (selector.select() > -1) {
// Wait for an event one of the registered channels
// Iterate over the set of keys for which events are available
Iterator selectedKeys = selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
try {
if (!key.isValid()) {
continue;
}
if (key.isConnectable()) {
connect(key);
}
// Check what event is available and deal with it
if (key.isAcceptable()) {
accept(key);
}
if (key.isReadable()) {
read(key);
}
if (key.isWritable()) {
write(key);
}
} catch (Exception e) {
e.printStackTrace();
close(key);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
在读/写部分,我检查是否有要读/写的东西,如果没有 - 然后我尝试关闭频道:
if (channel.read(attachment.buffer) < 1)
close(key);
关闭方法:
private void close(SelectionKey key) throws IOException {
key.cancel();
key.channel().close();
}
但是在处理此代码期间,我在主循环中遇到异常(它被捕获但我认为有问题)我得到了这个堆栈跟踪:
java.nio.channels.CancelledKeyException
at sun.nio.ch.SelectionKeyImpl.ensureValid(Unknown Source)
at sun.nio.ch.SelectionKeyImpl.readyOps(Unknown Source)
at java.nio.channels.SelectionKey.isWritable(Unknown Source)
因此,当进入写入部分时,它在主循环上失败,关闭通道并在“可写”部分返回主循环,并因此类异常而失败。有什么建议么?