这样的事情怎么样?
public static boolean isReadyForRead(SocketChannel socket) throws IOException {
return isReady(socket, SelectionKey.OP_READ);
}
public static boolean isReadyForWrite(SocketChannel socket) throws IOException {
return isReady(socket, SelectionKey.OP_WRITE);
}
public static boolean isReady(SocketChannel socket, int op) throws IOException {
// Setup
if (socket.isBlocking())
throw new IllegalArgumentException("Socket must be in non-blocking mode");
Selector selector = SelectorProvider.provider().openSelector();
socket.register(selector, op);
// Real work
if (selector.selectNow() == 0)
return false;
// Just in case selector has other keys
return selector.selectedKeys().contains(socket.keyFor(selector));
}
这个调用非常低效,因为它每次都进行设置。如果您有一个封闭类,则应将其移出。如果您知道选择器只包含一个键,则可以将最后一行更改为“ return true;
”。
我这样做只是为了好玩。我想不出这会有用的场景。Select() 旨在有效地告诉您套接字的状态,每个人都应该直接使用它。