下面的代码显示了一小块代码,它试图接受来自客户端的连接(使用java NIO的典型实现),但是当我尝试从Iterator中删除SelectionKey时,它会抛出异常。
此代码与Jenkov tutorial和另一个Acceptor (line 270) SocketServer from Apache Kafka非常相似。
override def run(): Unit = {
this.logger.info("Acceptor started.")
super.run()
this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT)
while (this.isRunning) {
val readyKeys = this.selector.select(500)
if (readyKeys > 0) {
val selectedKeys = this.selector.keys()
val selectionKeysIterator = selectedKeys.iterator()
while (selectionKeysIterator.hasNext && this.isRunning) {
val selectionKey = selectionKeysIterator.next()
selectionKeysIterator.remove()
if (!selectionKey.isAcceptable)
throw new IllegalStateException("The SelectionKey is not on the valid state [Acceptable].")
this.accept(selectionKey)
}
}
}
this.selector.close()
}
答案 0 :(得分:2)
选择键集由selector.selectedKey返回(你有select.keys,指定为不可修改)