【发布时间】:2013-06-11 07:17:49
【问题描述】:
如何让java.nio.channels.SelectionKey 对 NO opts 感兴趣?
SelectionKey#cancel()有可能,但不是很好,因为它使密钥无用。
SelectionKey 有 interestOps 常量; OP_ACCEPT、OP_CONNECT、OP_READ 和 OP_WRITE,但不是 OP_NOTHING。
那么拨打SelectionKey#interestOpts(**0**)合法操作吗?
这是一个例子。
for(;;) {
selector.select();
for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();
it.hasNext();) {
SelectionKey key = it.next(); it.remove();
key.interestOps(0); // interested in no opts.
// another thread handles socket...
worker.handle();
}
updateKeys(); // if the worker completes handling,
// other interestOpts are set...
}
到目前为止,此代码对我有效,但我怀疑调用 SelectionKey#interestOpts(0) 是否合法。
或者您能告诉我您的最佳做法吗?
【问题讨论】:
-
是的,0 是这样做的。