简体   繁体   中英

Java nio SelectionKey.register and interestops

I have been working on Java NIO communications and reading various writeups regarding this. 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.
  2. The only thing that can deliver you an OP_READ or OP_WRITE is a 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. It rarely if ever makes sense to register for OP_READ and OP_WRITE at the same time.

The validOps() method tells you which operations are valid for a given channel, not that you should need to know at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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