public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
SocketChannel socketChannel = SocketChannel.open();
//The Channel must be in non-blocking mode to be used with a Selector.
// This means that you cannot use FileChannel's with a Selector since FileChannel's cannot be switched into non-blocking mode.
// Socket channels will work fine though.
socketChannel.configureBlocking(false);
//If you are interested in more than one event, OR the constants together, like this:
int interestSet = SelectionKey.OP_ACCEPT;
SelectionKey selectionKey = socketChannel.register(selector, interestSet);
int interestSets = selectionKey.interestOps();
boolean isInterestedInAccept = (interestSets & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT;
System.out.println("flag: " + isInterestedInAccept);
}
报错:
Connected to the target VM, address: '127.0.0.1:51931', transport: 'socket'<br /> Exception in thread "main" java.lang.IllegalArgumentException<br /> at java.nio.channels.spi.AbstractSelectableChannel.register(AbstractSelectableChannel.java:199)<br /> at java.nio.channels.SelectableChannel.register(SelectableChannel.java:280)<br /> at com.deodar.web.controller.nio.SelectorTest.main(SelectorTest.java:31)<br /> Disconnected from the target VM, address: '127.0.0.1:51931', transport: 'socket'
Process finished with exit code 1
源码:
public final SelectionKey register(Selector sel, int ops,
Object att)
throws ClosedChannelException
{
synchronized (regLock) {
if (!isOpen())
throw new ClosedChannelException();
if ((ops & ~validOps()) != 0)
throw new IllegalArgumentException();
if (blocking)
throw new IllegalBlockingModeException();
SelectionKey k = findKey(sel);
if (k != null) {
k.interestOps(ops);
k.attach(att);
}
if (k == null) {
// New registration
synchronized (keyLock) {
if (!isOpen())
throw new ClosedChannelException();
k = ((AbstractSelector)sel).register(this, ops, att);
addKey(k);
}
}
return k;
}
}