简体   繁体   English

Java nio SelectionKey.register和interestops

[英]Java nio SelectionKey.register and interestops

I have been working on Java NIO communications and reading various writeups regarding this. 我一直在从事Java NIO通信的工作,并阅读有关此内容的各种文章。 The document says that I could "or" ops that I am interested in. However, I haven't seen a single example of 该文件说,我可以“或”对自己感兴趣的操作。但是,我还没有看到有关

channel.register(selector,SelectionKey.OP_ACCEPT|SelectionKey.OP_READ|Selection.OP_WRITE)

Is this a bad idea? 这是一个坏主意吗?

Yep. 是的 It's wrong. 这是不对的。

  1. The only thing that can deliver you an OP_ACCEPT is a ServerSocketChannel. 可以为您提供OP_ACCEPT的唯一东西是ServerSocketChannel.
  2. The only thing that can deliver you an OP_READ or OP_WRITE is a SocketChannel or a DatagramSocketChannel. 可以为您提供OP_READ或OP_WRITE的唯一东西是SocketChannel or a DatagramSocketChannel.
  3. So there is no way a single channel can deliver you all three of those events. 因此,没有一个渠道可以为您提供所有这三个事件。 So there is no sense in registering for them all. 因此,没有必要全部注册。
  4. OP_WRITE is almost always ready. OP_WRITE几乎总是准备就绪。 It rarely if ever makes sense to register for OP_READ and OP_WRITE at the same time. 几乎没有必要同时注册OP_READ和OP_WRITE。

The validOps() method tells you which operations are valid for a given channel, not that you should need to know at runtime. validOps()方法告诉您哪些操作对于给定通道有效,而不是您在运行时需要知道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM